-3

Got difficult to figure this. Failed to call this.doA() from the callback of external Promise.

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() {
   }
}
ryc16
  • 21
  • 1
  • 4
  • Possible duplicate of [TypeScript "this" scoping issue when called in jquery callback](http://stackoverflow.com/questions/20627138/typescript-this-scoping-issue-when-called-in-jquery-callback) – Aleksey L. Aug 21 '16 at 13:59
  • Or any of dozens if not hundreds of other similar questions, which can be found with a google search for something like "javascript method callback this:". –  Aug 21 '16 at 14:01

1 Answers1

1

The context of this is different when the method myCallback is executed.

You have two options:

(1) Using an arrow function:

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

(2) Using the Function.prototype.bind function:

HelloPromise.get({ callbackA: this.myCallback.bind(this) }).then(...)
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299