use*_*757 9 javascript lambda inheritance typescript
我有一个继承的类,并且需要父类具有一个虚方法,该方法在子类中被重写.这个方法是从基础构造函数调用的,需要访问实例属性,所以它需要是一个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");
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
派生的init
Base initLambda
Nit*_*mer 12
好吧,你不能拥有那个.
有一个问题已经打开,但它被关闭为"按设计".
你应该使用常规方法:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
然后它会工作.
至于保持正确this,你总是可以作为箭头函数调用方法:
doit() {
setTimeout(() => this.init(), 1);
}
Run Code Online (Sandbox Code Playgroud)
或者使用Function.prototype.bind函数:
setTimeout(this.init.bind(this));
Run Code Online (Sandbox Code Playgroud)
此外,_this打字稿编译器产生的东西只是对ES5的箭头函数进行polyfil的黑客攻击,但是如果你将目标更改为ES6则它不会使用它.
您可以将绑定方法保存为成员:
class Base {
...
public boundInit: () => void;
constructor() {
...
this.boundInit = this.initLambda.bind(this);
setTimeout(this.boundInit, 500);
}
...
Run Code Online (Sandbox Code Playgroud)
有了它,当我这样做时new Derived(),我得到的是:
派生的init
衍生的initLambda //在200毫秒之后
| 归档时间: |
|
| 查看次数: |
15973 次 |
| 最近记录: |