小编Bre*_*ent的帖子

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

我遇到了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方法?

提前致谢 :)

javascript typescript

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

javascript ×1

typescript ×1