typescript - 如何正确覆盖 typescript 中的方法?

标签 typescript inheritance this

为什么是 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/

相关文章:

typescript - 为什么在 typescript 中实现接口(interface)时必须重新声明类型

java - Java中类A继承类B时堆中发生了什么

javascript - 通过 addEventListener 传递它

javascript - 为什么使用 setTimeout 可以显示图表

typescript - 如何根据数组的值定义类型?

javascript - 有人可以用更外行的术语解释什么是 util.inherits 吗?

java - 将功能委托(delegate)给 Java 中的子类

c# - "this"这个词是什么意思, "static"是什么意思?

javascript - typescript 错误 :Type 'number' is not assignable to type 'never'