我有一个包含函数private receiveCheck
和protected dispatch
的类。我还想在回调中调用私有函数,我试图将其绑定到this
。
protected dispatch(ajaxParams: JQuery.AjaxSettings<any>): void {
ajaxParams.success = ((a: any, b: any) => {
console.log(this)
this.receiveCheck(0)
}).bind(this)
$.ajax(ajaxParams);
}
不幸的是,当执行匿名函数时,它将引发以下错误:
未捕获的TypeError:_this.receiveCheck不是函数
编辑:输出中的日志是Window对象。删除bind
调用不能解决此问题。
答案 0 :(得分:1)
如何运行dispatch
方法?使用箭头方法来避免丢失
public dispatch = (): void => {
// ...
}
答案 1 :(得分:0)
您使用了arraow函数,因此此上下文始终绑定到上层函数。您只需删除绑定
class Example {
public do() {
console.log('doPublic');
const fn = () => {
this.doProtected();
};
fn();
}
protected doProtected() {
console.log('doProtected');
}
}
const e = new Example();
console.log('start');
e.do();