在 ES6 中,您可以通过this.constructor以下方式引用静态方法:
class MainClass {
static info() {
return "This is some information";
}
constructor() {
this.info = this.constructor.info(); // Allows subclass to define different '.info()' method.
}
}
class ChildClass extends MainClass {
static info() {
return "This information is from the child";
}
constructor() {
super();
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在 TypeScript 中做到这一点?我希望能够覆盖超类的静态方法并从子类中使用它,而无需在实例方法中重新定义引用。现在,我知道如何在 TypeScript 中访问静态方法的唯一方法是使用类名。
MainClass.info();
Run Code Online (Sandbox Code Playgroud)
但是如果我这样做,子类将继续使用MainClass.info();而不是它自己的.info()方法。