Next →

Understanding this in JavaScript

The value of this depends on how a function is called, and it can be tricky to understand.

Global Context

In the global scope, this refers to the global object (window in browsers).

console.log(this); // window (in browsers)

Object Method

When a function is called as a method of an object, this refers to that object.

const obj = {
  name: 'Alice',
  greet() {
    console.log(this.name);
  }
};
obj.greet(); // Alice

Alone or in a Regular Function

In strict mode, this is undefined inside a function not called as an object method.

function show() {
  console.log(this);
}
show(); // undefined (in strict mode)

Arrow Functions

Arrow functions do not have their own this. They inherit this from the surrounding (lexical) scope.

const obj = {
  name: 'Bob',
  greet: () => {
    console.log(this.name);
  }
};
obj.greet(); // undefined (because `this` is from outside)