我有一个继承类,需要父类有一个虚方法,在子类中重写。这个方法是从基础构造函数调用的,需要访问实例属性,所以它需要是一个lambda函数,所以“this”是“_this”。问题是,覆盖 lambda 方法对我来说不像覆盖非 lambda 方法那样有效。这可能吗?如果不是,我想了解原因。
此外,当仅从构造函数调用该方法时,“this”是否始终与“_this”相同?
class Base {
protected prop = null;
constructor() {
this.init();
this.initLambda();
}
init() {
console.log("Base init");
}
initLambda = () => {
console.log("Base initLambda");
}
}
class Derived extends Base {
constructor() {
super();
}
init() {
console.log("Derived init");
}
initLambda = () => {
//let x = this.prop;
console.log("Derived initLambda");
}
}
输出:
派生初始化
基础 initLambda
最佳答案
好吧,你不能拥有那个。
有 an issue that was opened但它是“按设计”关闭的。
你应该使用常规方法:
class Base {
protected prop = null;
constructor() {
this.init();
this.initLambda();
}
init() {
console.log("Base init");
}
initLambda() {
console.log("Base initLambda");
}
}
class Derived extends Base {
constructor() {
super();
}
init() {
console.log("Derived init");
}
initLambda() {
console.log("Derived initLambda");
}
}
然后它就会起作用。
至于保持正确的 this
,您始终可以将调用作为箭头函数传递给该方法:
doit() {
setTimeout(() => this.init(), 1);
}
或者使用 Function.prototype.bind功能:
setTimeout(this.init.bind(this));
另外,typescript 编译器生成的 _this
只是一个 polyfil ES5 箭头函数的 hack,但如果你将目标更改为 ES6,那么它就不会使用它。
编辑:
您可以将绑定(bind)的方法保存为成员:
class Base {
...
public boundInit: () => void;
constructor() {
...
this.boundInit = this.initLambda.bind(this);
setTimeout(this.boundInit, 500);
}
...
这样,当我执行 new Derived()
时,这就是我得到的:
Derived init
Derived initLambda // after 200 millis
关于javascript - TypeScript - 如何继承类和覆盖 lambda 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38640961/