MediumConcept

How does the this keyword work in JavaScript?

Technology:
JavaScript
Experience:
Junior,
Mid-level

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.

Detailed explanation

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.

Example

javascript
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

Follow-up questions

  • What is the difference between call, apply and bind?
  • How does this behave inside a class method used as an event handler?
  • JavaScriptEasy

    What is hoisting in JavaScript?

    Hoisting is JavaScript moving declarations to the top of their scope during compilation, so functions and var variables can be referenced before the line where they are written.

    Intern · Junior · Functions & Scope
  • JavaScriptMedium

    What is a closure in JavaScript and why is it useful?

    A closure is a function that keeps access to the variables of the scope where it was created, even after that outer function has finished running.

    Junior · Mid-level · Functions & Scope
  • JavaScriptMedium

    What is prototypal inheritance in JavaScript?

    In JavaScript every object has an internal link to another object called its prototype, and property lookups walk up this prototype chain until the property is found or the chain ends.

    Mid-level · Senior · Object-Oriented Programming