我有一个继承的类,并且需要父类具有一个虚方法,该方法在子类中被重写.从基础构造函数调用此方法,并且需要访问实例属性,因此它需要是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");
}
}
输出:
派生的init
基础initLambda
解决方法
好吧,你不能拥有那个.
有 an issue that was opened但它被关闭为“按设计”.
有 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");
}
}
然后它会工作.
至于保持正确,你总是可以作为箭头函数调用方法:
doit() {
setTimeout(() => this.init(),1);
}
或使用Function.prototype.bind功能:
setTimeout(this.init.bind(this));
此外,打字稿编译器生成的这个东西只是对ES5的箭头函数进行polyfil的黑客攻击,但是如果你将目标更改为ES6则它不会使用它.
编辑:
您可以将绑定方法保存为成员:
class Base {
...
public boundInit: () => void;
constructor() {
...
this.boundInit = this.initLambda.bind(this);
setTimeout(this.boundInit,500);
}
...
有了它,当我做新的Derived()时,这就是我得到的:
Derived init Derived initLambda // after 200 millis