TypeScript - 如何继承类并覆盖lambda方法 [英] TypeScript - how to inherit class and override lambda method
问题描述
我有一个继承的类,并且需要父类具有一个虚方法,该方法在子类中被重写。这个方法是从基础构造函数调用的,需要访问实例属性,所以它需要是一个lambda函数,所以this就是_this。问题是,覆盖lambda方法对我来说不起作用,就像重写非lambda一样。这可能吗?如果没有,我想了解原因。
I have an inherited class, and need the parent to have a virtual method, which is overridden in the child class. This method is called from the base constructor, and needs access to instance properties, so it needs to be a lambda function, so "this" is "_this". The problem is, overriding a lambda method does not work for me like overriding a non-lambda does. Is this possible? If not, I'd like to understand why.
此外,当仅从构造函数调用方法时,this是否始终与_this相同?
Also, will "this" always be the same as "_this" when the method is only called from the constructor?
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
Output:
Derived init
Base initLambda
推荐答案
好吧,你不能拥有它。
有已打开的问题,但已按按设计关闭。
Well, you can't have that.
There's an issue that was opened but it was closed as "by design".
你应该使用常规方法:
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");
}
}
然后它会起作用。
至于保持正确这个
,你总是可以像箭头函数那样调用方法:
As for keeping the right this
, you can always pass a call to the method as an arrow function:
doit() {
setTimeout(() => this.init(), 1);
}
或者使用 Function.prototype.bind 功能:
setTimeout(this.init.bind(this));
此外,打字稿的 _this
编译器生成只是对ES5的箭头函数进行polyfil的黑客攻击,但是如果你将目标更改为ES6则它将不会使用它。
Also, the _this
thing that the typescript compiler produces is just a hack to polyfil the arrow functions for ES5, but if you change the target to ES6 then it won't use it.
您可以将绑定方法保存为成员:
You can save the bound methods as members:
class Base {
...
public boundInit: () => void;
constructor() {
...
this.boundInit = this.initLambda.bind(this);
setTimeout(this.boundInit, 500);
}
...
有了这个,当我做 new Derived()
这就是我得到的:
With that, when I do new Derived()
this is what I get:
派生的init
派生的initLambda //在200毫秒之后
Derived init
Derived initLambda // after 200 millis
这篇关于TypeScript - 如何继承类并覆盖lambda方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!