learn deep. ship safe.Practice testsFollow ByteMunSubscribe

Concept

The this keyword

The object a function is called on, decided at call time (except in arrow functions).

The this keyword explained

In JavaScript, this is decided by how a function is called, not where it is written. Called as a method (obj.fn()), this is obj; called with new, it is the new object; called with call, apply or bind, it is whatever you pass; called as a plain function, it is undefined in strict mode. Arrow functions are the exception: they have no this of their own and use the one from the surrounding code.

The rules, in order of priority

  1. new: this is the newly created object.
  2. Explicit: fn.call(obj), fn.apply(obj) or a function from fn.bind(obj).
  3. Method call: obj.fn() sets this to obj.
  4. Plain call: fn() gives undefined in strict mode and modules (the global object in sloppy scripts).
  5. Arrow functions skip all of the above and take this from where they were defined.
const user = {
  name: "Asha",
  hello() { return `Hi, ${this.name}`; },
};
user.hello();              // "Hi, Asha"
const fn = user.hello;
fn();                      // TypeError in strict mode: this is undefined

class Timer {
  seconds = 0;
  start() {
    setInterval(() => { this.seconds += 1; }, 1000); // arrow keeps the instance
  }
}

Common mistakes

  • Losing this when passing a method as a callback (button.onclick = obj.handle). Use an arrow wrapper or bind.
  • Using an arrow function as an object method and expecting this to be the object.
  • Forgetting new with a constructor function, so this is not a fresh object.

What interviewers ask about this

  • "What will this be here?" Find the call site and apply the rules above.
  • "call, apply or bind?" call and apply invoke now (arguments listed or as an array); bind returns a new function for later.
  • "Why do arrow functions help in callbacks?" They keep the outer this.
Concept map
Learn firstObjects
The this keywordCompared withArrow functions

What should you learn before The this keyword?

  1. ObjectsCollections of key–value properties, the building block of most JavaScript data.

Connections to other concepts

Compared with
Arrow functions

Practise The this keyword

All topics