TypeScript 绑定上下文

TypeScript bind context

我有一个 class 包含函数 private receiveCheckprotected 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);
}

不幸的是,执行匿名函数时,抛出以下错误:

Uncaught TypeError: _this.receiveCheck is not a function

编辑:输出中的日志是 Window 对象。删除 bind 调用并不能解决此问题。

你用了箭头函数,反正这个上下文是绑定到upper函数的。您可以简单地删除 bind

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();

https://codepen.io/ste-xx/pen/qzaeRx?editors=1111

你如何运行 dispatch 方法?使用箭头方法避免丢失 this

    public dispatch = (): void =>  {
      // ...
    }