Pseudo Random Nonsense Generator

This in Javascript

· note

ref

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:

  1. new — this is a fresh object created for the call. Assignments inside the constructor (this.value = 10) land on it.
  2. call / apply / bind — this is whatever object is passed as the first argument. bind fixes it for later; call and apply fix it for that invocation.
  3. method call (dot notation) — this is the object to the left of the dot. obj.printThis() gives this === obj.
  4. free call — anything not covered above: this is the global object, window in a browser. The reason is that a function declared at top level is really a property of the global object, so fn() === window.fn() — rule 4 is rule 3 in disguise.
  5. 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.