0

I have a class containing function private receiveCheck and protected dispatch. I also want to call the private function in a callback, which I tried to bind to this.

protected dispatch(ajaxParams: JQuery.AjaxSettings<any>): void {
    ajaxParams.success = ((a: any, b: any) => {
        console.log(this)
        this.receiveCheck(0)
    }).bind(this)

    $.ajax(ajaxParams);
}

Unfortunately when the anonymous function is executed, it throws the following error:

Uncaught TypeError: _this.receiveCheck is not a function

EDIT: The log in the output is the Window object. Removing the bind call does not solve this problem.

Vilda
  • 1,675
  • 1
  • 20
  • 50

2 Answers2

1

How do you run the dispatch method? Use arrow method to avoid loosing this

    public dispatch = (): void =>  {
      // ...
    }
aquz
  • 246
  • 1
  • 3
  • It is run from the subclass via `super.dispatch(..)`. (`this.dispatch` did not work) Changing the function to arrow method generates compile time error: `Only public and protected methods of the base class are accessible via the 'super' keyword.` – Vilda Jun 19 '19 at 09:41
  • Let's go deeper :) How do run this subclass method? It is callback? – aquz Jun 19 '19 at 09:56
  • Yes. It is called in a function, which is invoked via `setTimeout`. – Vilda Jun 19 '19 at 09:57
  • Ok, so change the subclass method to arrow. – aquz Jun 19 '19 at 09:59
  • That did the trick. :-) Could you please provide an explanation in your answer? – Vilda Jun 19 '19 at 10:00
  • Sure :) https://stackoverflow.com/a/2130411/11610862 - when you call the method via `setTimeout` it loses `this` context, but not `super`, so the problem only appears in the `dispatch` method. You can look at typescript output code, to understand how `super` works. – aquz Jun 19 '19 at 10:17
0

You use an arraow function, so the this context is binded to the upper function anyway. You could simply remove the 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

ste-xx
  • 320
  • 1
  • 10