Skip to content

this keyword

Daisho Komiyama edited this page Mar 16, 2024 · 10 revisions

Remembering the behavior of the this keyword can be tricky, so here's a quick reference:

Regular functions

In regular functions, the value of this is determined by the object on which the function is invoked.

function logThis() {
  console.log(this);
}

const obj = {
  logThis
};

logThis(); // window
obj.logThis(); // obj

Arrow functions

For arrow functions, this is determined by the lexical environment in which the arrow function is defined.

const logThis = () => {
  console.log(this);
};

const obj = {
  logThis
};

logThis(); // window (where the function was defined)
obj.logThis(); // window (where the function was defined)

Classes

The value of the this keyword is constructor functions or classes is the value of the newly created instance.

class User {
  getThis() {
    return this
  }
}

const user1 = new User();
const user2 = new User();

user1.getThis(); // user1
user2.getThis(); // user2

Strict mode

The value of the this keyword is undefined by default. This behavior applies in modules.

"use strict"

function logThis() {
  console.log(this)
}

const obj = {
  logThis,
  logThis2() {
    logThis()
  }
}

logThis() // undefined
obj.logThis() // obj
obj.logThis2() // undefined
Clone this wiki locally