打字稿覆盖构造函数中的扩展属性

Bre*_*ent 6 javascript typescript

我遇到了Typescript的问题,我扩展了一个类并从super覆盖了一个属性,但是当我实例化子类时,仍然在构造函数中读取了超类属性.请看下面的例子:

class Person {

    public type:string = 'Generic Person';

    public constructor() {
        console.log(this.type);
    }

}

class Clown extends Person {

    public type:string = 'Scary Clown';

}

var person = new Person(), // 'Generic Person'
    clown = new Clown(); // 'Generic Person'

console.log(person.type); // 'Generic Person'
console.log(clown.type); // 'Scary Clown'
Run Code Online (Sandbox Code Playgroud)

当我实例化一个小丑的实例时,我的预期行为将是"可怕的小丑".有没有其他方法可以实现这一点,而无需将值传递给构造函数本身或具有某种我在实例化后手动触发的init方法?

提前致谢 :)

bas*_*rat 6

在手动输入构造函数的主体之前,属性初始值设定项将插入构造函数的顶部.所以

class Person {
    public type:string = 'Generic Person';
    public constructor() {
        console.log(this.type);
    }
}
Run Code Online (Sandbox Code Playgroud)

var Person = (function () {
    function Person() {
        this.type = 'Generic Person';
        // NOTE: You want a different value for `type`
        console.log(this.type);
    }
    return Person;
})();
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,使用属性初始值设定项无法type在父构造函数体中获得不同的内容.

或者,不要使用type和依赖内置constructor属性:

interface Function{name?:string;}

class Person {    
    public constructor() {
        console.log(this.constructor.name);
    }
}

class Clown extends Person {    
}

var person = new Person(), // 'Person'
    clown = new Clown(); // 'Clown'

console.log(person.constructor.name); // 'Person'
console.log(clown.constructor.name); // 'Clown'
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您缩小代码(应该这样做),则 this.constructor.name 将变成类似于“n”的内容 (2认同)