This in Javascript
ref
- https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3 (Arnav Aggarwal, Jun 2017)
summary
this is not lexical and not set by where the function is written. It is decided at the call site,
and the rules apply in strict precedence order:
new—thisis a fresh object created for the call. Assignments inside the constructor (this.value = 10) land on it.call/apply/bind—thisis whatever object is passed as the first argument.bindfixes it for later;callandapplyfix it for that invocation.- method call (dot notation) —
thisis the object to the left of the dot.obj.printThis()givesthis === obj. - free call — anything not covered above:
thisis the global object,windowin a browser. The reason is that a function declared at top level is really a property of the global object, sofn() === window.fn()— rule 4 is rule 3 in disguise. - highest applicable rule wins if several could describe the same call.
Arrow functions opt out. They ignore all of the above and take this from the enclosing scope
at the moment they are created — read the line above the arrow’s definition and that is its this.
That is why an arrow inside a method keeps the method’s this, and why an arrow used as a
constructor or prototype method quietly breaks.
why it is worth keeping
Written while working in a React class-component codebase, where the same failure shows up as
this.setState is not a function after passing a handler into a callback. The callback is a free
call (rule 4), so this is window, not the component.