How does the this keyword work in JavaScript?
Quick answer
this is decided by how a function is called, not where it is written: as a method it is the object before the dot, with new it is the new object, and arrow functions inherit it from the enclosing scope.
For a normal function there are four rules, applied in this order: new Foo() makes this the newly created object; call, apply or bind set it explicitly; obj.method() makes this the object before the dot; otherwise it is undefined in strict mode (or the global object in sloppy mode).
Arrow functions do not have their own this. They use the this of the scope they were defined in, which is why they are handy for callbacks inside methods. The classic bug is passing obj.method as a callback: the call site changes, so this is lost.
const user = {
name: "Asha",
regular() { return this.name; },
arrow: () => typeof this, // "this" is NOT user here
};
user.regular(); // "Asha"
const detached = user.regular;
detached(); // undefined (or TypeError) - lost context
detached.call({ name: "Ravi" }) // "Ravi"
user.regular.bind(user)(); // "Asha"Key points
- this depends on the call site
- call, apply and bind set this explicitly
- Arrow functions capture this lexically and cannot be rebound
Questions interviewers ask next
- What is the difference between call, apply and bind?
- How does this behave inside a class method used as an event handler?