我尝试从Callback中的扩展类中访问一个方法:
Model.findOne( { _id: id }, function( err, rec ){
super.handleFind( err, rec );
});
当我编译我的Typescript时,我看到以下错误:
error TS2660: 'super' can only be referenced in members of derived classes or object literal expressions.
当我运行JavaScript时,我得到:
TypeError: Cannot read property 'call' of undefined
如果 - 在回调之前 - 我做的事情就像让 fct = super.handleFind; 似乎有效,但这个在handleFind()中是未定义的 - 并且我需要这个上下文。
答案 0 :(得分:2)
假设handleFile
在父类中定义,它将由您的子类继承,除非您在子类中重写handleFile
并且想要使用handleFile
的实现相反,从超类中,您可以使用this.handleFile
调用它。
第二个问题是,如果要保留function() {...}
上下文(使其指向子类的当前实例),则将Model.findOne
回调传递给this
,请改用箭头功能,将功能更改为
// Use arrow function to make 'this' point to the current instance of the
// enclosing class
Model.findOne( { _id: id }, ( err, rec ) => {
super.handleFind( err, rec );
});
答案 1 :(得分:-1)
您可以使用Function.prototype.call()
来调用传递给.findOne()
的匿名函数,并将上下文设置为this
:Model
class
class Test {
constructor() {}
handleFind(err, rec) {
console.log(err, rec)
}
}
class Model extends Test {
constructor() {
super()
}
findOne(id, fn) {
fn.call(this, id, "err")
}
}
var model = new Model();
model.findOne({id: 123}, function(err, rec) {
this.handleFind(err, rec)
});