Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 类型脚本重写构造函数中的扩展属性_Javascript_Typescript - Fatal编程技术网

Javascript 类型脚本重写构造函数中的扩展属性

Javascript 类型脚本重写构造函数中的扩展属性,javascript,typescript,Javascript,Typescript,我在Typescript中遇到了一个问题,我扩展了一个类并重写了一个来自super的属性,但是当我实例化子类时,super类属性仍然在构造函数中读取。请参见以下示例: class Person { public type:string = 'Generic Person'; public constructor() { console.log(this.type); } } class Clown extends Person { pub

我在Typescript中遇到了一个问题,我扩展了一个类并重写了一个来自super的属性,但是当我实例化子类时,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'
当我实例化一个小丑实例时,我预期的行为将是“可怕的小丑”。有没有其他方法可以实现这一点,而无需将值传递到构造函数本身,或者在实例化后手动启动某种init方法


提前感谢:)

属性初始值设定项插入到构造函数顶部,位于手动输入的构造函数主体之前。所以

class Person {
    public type:string = 'Generic Person';
    public constructor() {
        console.log(this.type);
    }
}
变成

var Person = (function () {
    function Person() {
        this.type = 'Generic Person';
        // NOTE: You want a different value for `type`
        console.log(this.type);
    }
    return Person;
})();
如您所见,无法使用属性初始值设定项在父构造函数体中获取不同的
类型

或者,不要使用
类型
并依赖内置的
构造函数
属性:

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'

谢谢你,巴萨拉特。这在属性与类名相同的情况下有效,但在其他情况下不起作用。但正如您所提到的,它目前的工作方式是不可能的。请注意,如果您缩小代码(您应该这样做),this.constructor.name将变成类似“n”的内容