How does the this keyword work in JavaScript, and how do arrow functions change it?
this is decided by how a function is called, not where it is written. There are five rules, checked in order:
- new binding — called with
new,thisis the newly created object. - Explicit binding —
call,applyorbindset it directly. - Method binding — called as
obj.method(),thisisobj. Note that this is about the call site, so pulling the method out into a variable loses it. - Default binding — a plain call gets the global object, or
undefinedin strict mode and in modules. - Arrow functions break the pattern entirely. They have no
thisof their own and inherit it lexically from the enclosing scope at definition time.call,applyandbindcannot change it.
That is exactly why arrows are the standard fix for callbacks:
// loses this
setTimeout(function () { this.tick(); }, 100);
// keeps this
setTimeout(() => this.tick(), 100);Note: The corollary is that an arrow function should never be used as an object method or a constructor, because there is no useful this to inherit.





