来自promise的typescript回调和访问'this'

时间:2016-08-21 13:52:54

标签: typescript

很难想象这一点。无法从外部Promise的回调中调用this.doA()。

class A {
    private _startCallback;

    // register callbacks
    constructor({startCallback}) {
        this._startCallback = startCallback;
    }
   load() {
       // A external promise.
       HelloPromise.get({callbackA: myCallback}).then(...)
   }

   private myCallback() {
      // FAILED to Call doA
      this.doA() 
   }
   private doA() {
   }
}

1 个答案:

答案 0 :(得分:1)

执行方法thismyCallback的上下文不同。

您有两种选择:

(1)使用arrow function

HelloPromise.get({ callbackA: () => { this.myCallback(); } }).then(...)

(2)使用Function.prototype.bind功能:

HelloPromise.get({ callbackA: this.myCallback.bind(this) }).then(...)
相关问题