Skip to the content

Lesson 55 of 296

How this is set

What you will learn

  • What this is
  • The four rules that set this, and their order
  • How arrow functions handle this
  • How this gets "lost"
  • this in event listeners and classes
On this page

What is this?

this is a special word inside a function. It refers to an object, and which object depends on how the function is called, not where it is written.

This is the opposite of normal variables, which use lexical scope (Lesson 50). That difference is why this confuses people.

Rule 1: method call (implicit binding)

When a function is called as a method, with a dot, this is the object before the dot.

const user = {
  name: "Sam",
  greet() {
    return `Hi, I am ${this.name}`;
  }
};

user.greet();        "Hi, I am Sam"

The same function on another object gets a different this:

const other = { name: "Ali", greet: user.greet };
other.greet();       "Hi, I am Ali"

Rule 2: plain call (default binding)

When a function is called on its own, with nothing before the dot:

function show() {
  console.log(this);
}
show();
  • In strict mode (which includes all ES modules and classes): this is undefined.
  • In old non-strict scripts: this is the global object (window in browsers).

Rule 3: call, apply or bind (explicit binding)

You can choose this yourself (Lesson 56):

function greet() {
  return `Hi, ${this.name}`;
}
greet.call({ name: "Sam" });      "Hi, Sam"

Rule 4: new (constructor call)

When a function is called with new, JavaScript creates a brand new empty object and sets this to it:

function User(name) {
  this.name = name;
}
const u = new User("Sam");
u.name;      "Sam"

Order of the rules

When more than one could apply, this order wins:

  1. new
  2. Explicit: bind / call / apply
  3. Implicit: method call with a dot
  4. Default: plain call

Arrow functions: no own this

Arrow functions do not have their own this. They use the this of the code around them, where they were written (lexical this). The four rules above do not apply to them, and call, apply and bind cannot change it.

const timer = {
  seconds: 0,
  start() {
    setInterval(() => {
      this.seconds++;          this is timer, from start()
    }, 1000);
  }
};
timer.start();

With a normal function instead of the arrow, this inside the callback would be undefined (strict mode), because setInterval calls it as a plain function.

Arrow functions as methods: the trap

const user = {
  name: "Sam",
  greet: () => `Hi, ${this.name}`
};
user.greet();        "Hi, undefined"

The arrow function takes this from outside the object (the module or global scope), not from user. Do not use arrow functions as object methods that need this.

Losing this

The most common this bug: taking a method off its object.

const user = {
  name: "Sam",
  greet() {
    return `Hi, ${this.name}`;
  }
};

const fn = user.greet;
fn();        TypeError: Cannot read properties of undefined

fn() is a plain call (rule 2), so this is undefined.

The same happens when you pass a method as a callback:

setTimeout(user.greet, 1000);                 loses this
button.addEventListener("click", user.greet); this becomes the button

Fixes:

setTimeout(() => user.greet(), 1000);         call it as a method inside an arrow
setTimeout(user.greet.bind(user), 1000);      bind this permanently

this in event listeners

With a normal function, this is the element the listener is attached to:

button.addEventListener("click", function () {
  this.classList.add("clicked");       this is the button
});

With an arrow function, this is whatever it was outside. Use event.currentTarget instead; it always works:

button.addEventListener("click", (event) => {
  event.currentTarget.classList.add("clicked");
});

this in classes

Inside class methods, this is the instance (the object made with new). But methods still lose this when passed as callbacks. A common fix is an arrow function class field:

class Clock {
  seconds = 0;
  tick = () => {
    this.seconds++;
  };
}
const c = new Clock();
setInterval(c.tick, 1000);       works: tick always uses this instance

Quick decision guide

To find this, look at how the function is called:

  1. Is it an arrow function? Use the this from where it was written.
  2. Called with new? The new object.
  3. Called with call, apply, or is it a bound function? The object given.
  4. Called as something.fn()? something.
  5. Otherwise: undefined in strict mode.

Common mistakes

  • Arrow functions as object methods.
  • Passing obj.method as a callback and losing this.
  • Expecting this to follow lexical scope like variables.

How to say it in an interview

"this is decided by how a function is called. With new it is the new object; with call, apply or bind it is the object passed; as a method call it is the object before the dot; and as a plain call it is undefined in strict mode. Arrow functions do not have their own this and take it lexically from the surrounding scope, which makes them good for callbacks but bad as object methods. The most common bug is passing a method as a callback, which loses this; I fix it with bind or a wrapping arrow function."

Key words

WordMeaning
thisA reference set by how a function is called
Implicit bindingthis is the object before the dot
Default bindingPlain call: undefined in strict mode
Explicit bindingSetting this with call, apply or bind
new bindingthis is a newly created object
Lexical thisArrow functions using the this of the surrounding code
Strict modeA safer mode of JavaScript, on by default in modules and classes

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.