__extends继承Array时,不符合预期
Open
Nobody has claimed this yet.
question
- Dominant language
- TypeScript
- Stars
- 1.3k
- Forks
- 145
- PR merge metrics
- No merged PRs in 30d
Description
源码:
class B extends Array{
get width(): number {
return 20;
}
toString(): string {
return "class B";
}
}
const b1 = new B();
b1.push("kkkkk")
console.log(b1.toString());
console.log(b1.width);
//class B
//20
转译代码
(function(){
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var B = /** @class */ (function (_super) {
__extends(B, _super);
function B() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(B.prototype, "width", {
get: function () {
return 20;
},
enumerable: false,
configurable: true
});
B.prototype.toString = function () {
return "class B";
};
return B;
}(Array));
var b1 = new B();
b1.push("kkkkk")
console.log(b1.toString());
console.log(b1.width);
})();
// kkkkk
// undefined
b1.toString()走了 原生 Array 的 toString,原型链已经乱了。
对照babel的转译代码,得到的解决方案
// babel _wrapNativeSuper方法
// }(Array));
}(_wrapNativeSuper(Array)));
现在,他可以正常的工作了。
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the __extends helper shown in the issue and reproduce the Array subclass example. Compare its behavior with Babel's _wrapNativeSuper(Array) approach, then verify that the subclass preserves the expected toString and width behavior after compilation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100