gpt4 book ai didi

javascript - typescript 覆盖构造函数中的扩展属性

转载 作者:数据小太阳 更新时间:2023-10-29 05:33:16 24 4
gpt4 key购买 nike

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

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'

当我实例化 clown 的实例时,我预期的行为是“可怕的 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;
})();

如您所见,没有办法使用属性初始值设定项在父构造函数主体中获取不同的类型

或者不使用 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'

关于javascript - typescript 覆盖构造函数中的扩展属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27696982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com