【发布时间】:2021-06-09 19:30:28
【问题描述】:
为什么show() 方法中的this.fullName 为空?
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();
我应该如何解决这个问题?
【问题讨论】:
-
请详细说明输出是哪种语言
-
我已经在标签中指定了语言。并且输出已在代码中进行了注释。 @ArfatBinkileb
-
我的看法是,你不能在 super 调用中更改 children 的属性,因为到 super 时,children 的属性还不存在。
-
所以基本上
fullName的初始化发生在super调用之后,它会覆盖您在makeSir中设置的fullName。
标签: typescript inheritance this