这是我的代码:
class Animal {
constructor(public name: string){}
}
class Cat extends Animal {
constructor(public name: string) {
super(name);
}
}
它输出以下代码:
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Animal = (function () {
function Animal(name) {
this.name = name;
}
return Animal;
})();
var Cat = (function (_super) {
__extends(Cat, _super);
function Cat(name) {
_super.call(this, name);
this.name = name;
}
return Cat;
})(Animal);
正如您从 this demo 中看到的那样,构造函数
被枚举为键。
Cat类原型(prototype)的属性constructor
应该是不可枚举的,但是方法__extends改变了这一点。我该如何修复这个问题?
我知道下面的代码可以实现这一点,但我想要一种 TypeScript 原生支持的方式!
Object.defineProperty(Cat.prototype, 'constructor', {
enumerable: false
});
最佳答案
您需要定义自己的 __extends
变量,该变量使用 Object.create
而不是 new __()
来设置原型(prototype)链。
有一个功能请求允许您在全局级别执行此操作:https://github.com/Microsoft/TypeScript/issues/1622
关于javascript - TypeScript 中子类原型(prototype)的构造函数是可枚举的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30678764/