0

Maybe a lot of you will find this question trivial, but after 3 days of searching without any answer i found the answer by myself and maybe someone in the future will need this title above while searching google..

I must understand Why A works and B does not? why i can access my this.MarkContents_Input() function only as a delegate?

A.

refreshInputStatistics(): void {
        this.updateprocessing();
        setTimeout(() =>
            this.MarkContents_Input(this.vc.returnEditor(staticEditorDirective.textAreaEnum.LeftTextArea))
            ,50);
    }

B.

refreshInputStatistics(): void {
        this.updateprocessing();
        setTimeout(
            this.MarkContents_Input(this.vc.returnEditor(staticEditorDirective.textAreaEnum.LeftTextArea))
            ,50);
    }

I am very new to front end web development, maybe i am missing something(?)

EDIT: my question was marked as duplicate, yes i agree, now i see its duplicated, but search keywords here can help others in the future (as mentioned above, unfortunately 3 days of search did not lead my to the first question, could have saved me a lot of headache... )

Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52

1 Answers1

2

This is because how this works in Javascript and how fat arrow functions () => {} bind the this context. It can be very confusing to newcomers to Javascript. It is kind of a trap, but on the other hand it makes Javascript powerfull (you can use somefunction.call(somethingWhatReplacesThis, whateverArguments)

the A option is basically equivalent to something like this. I hope it make this more clear.

refreshInputStatistics(): void {
        this.updateprocessing();
        var that = this; // store context for usage in setTimeout
        setTimeout(            that.MarkContents_Input(that.vc.returnEditor(staticEditorDirective.textAreaEnum.LeftTextArea))
            ,50);
    }

Deeper explanation

The setTimeout() and other callback functions are evaluated in global context, where the this keyword points to the global object (usually window, but that depends on the environment in which the function is executed (Browser, NodeJs, Webworker...) So in order to make it work, you need to capture the context to a variable. The fat arrow function does it for you automatically, and transpiles to something similar to the example above.

Useful links

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this.

How does the "this" keyword work?

David Votrubec
  • 3,968
  • 3
  • 33
  • 44