javascript - TypeScript 中子类原型(prototype)的构造函数是可枚举的

标签 javascript typescript inheritance

这是我的代码:

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/

相关文章:

Java,接口(interface)可以继承吗?

javascript - 为什么我的 Prop 在我需要的时候不能在我的组件中使用?

javascript - 将用户输入直接保存到 JQuery 中的变量中

javascript - polymer 纸图标按钮不会触发点击

typescript - 限制 Typescript 中 if 语句中的赋值

c# - 将 Collection<Derived> 转换为 Collection<Base>

javascript - 当字段等于特定长度时如何调用JS函数?

angular - 无法绑定(bind)到 'videoId',因为它不是 'youtube-player' 的已知属性

Angular ngx-smart-popover 在条件下打开

go - 不同的结构重用相同的方法