Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

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, this is the newly created object.
  • Explicit bindingcall, apply or bind set it directly.
  • Method binding — called as obj.method(), this is obj. 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 undefined in strict mode and in modules.
  • Arrow functions break the pattern entirely. They have no this of their own and inherit it lexically from the enclosing scope at definition time. call, apply and bind cannot 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.

All Javascript interview questions

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as