为什么是 this.fullName
空在 show()
方法?
class Person {
protected name: string = "";
constructor(name: string) {
this.makeSir(name);
}
makeSir(name: string) {
this.name = "sir" + name;
}
}
class Man extends Person {
protected fullName = "";
constructor(name: string) {
super(name);
}
makeSir(name: string) {
super.makeSir(name);
this.fullName = "***" + name;
console.log(this.fullName);//[LOG]: "***john"
}
show() {
console.log(this.fullName);//[LOG]: ""
}
}
const man = new Man("john");
man.show();
我应该如何解决这个问题?
最佳答案
super()
在构造像您的 Man
这样的派生类时,总是首先调用它.这包括在您执行的任何变量初始化之前,例如 protected fullName = ''
.因此,虽然您的 Man.makeSir
正在调用和设置 fullName
到一个好的值,之后你的空字符串赋值开始并清除它的值。
避免这种延迟覆盖的一种方法是不对 fullName
设置初始值。 :
// give it a type because we don't give it an initial value
// use `!` syntax to hint to TypeScript that this will be initialized during the constructor
// even though TS cannot figure that out itself
protected fullName!: string;
现在既然你从来没有设置过 fullName
到“初始”值,您永远不会覆盖 super()
所做的工作称呼。
关于typescript - 如何正确覆盖 typescript 中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66588749/