Understanding this in JavaScript

A comprehensive guide to the this keyword and its behavior

What is this?

In JavaScript, this is a special keyword that refers to the context in which a function is executed. The value of this depends on how a function is called, not where it's defined.

Key Point: this is determined at runtime based on the invocation context.

Global Context

In the global execution context (outside any function), this refers to the global object.

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

Function Context

In a regular function call, this refers to the global object (or undefined in strict mode).

function myFunc() {
  console.log(this); // window (or undefined in strict mode)
}
myFunc();

Method Context

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

const person = {
  name: 'Alice',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

person.greet(); // "Hello, my name is Alice"

Constructor Context

When a function is used as a constructor (with the new keyword), this refers to the newly created object.

function Person(name) {
  this.name = name;
}

const alice = new Person('Alice');
console.log(alice.name); // "Alice"

Arrow Functions

Arrow functions don't have their own this context. Instead, they inherit this from the surrounding lexical context.

const person = {
  name: 'Alice',
  greet: () => {
    console.log(`Hello, my name is ${this.name}`);
  }
};

person.greet(); // "Hello, my name is undefined" 
// (this refers to the global object)

Explicit Binding

You can explicitly set the value of this using call(), apply(), or bind().

function greet() {
  console.log(`Hello, ${this.name}`);
}

const person1 = { name: 'Alice' };
const person2 = { name: 'Bob' };

greet.call(person1); // "Hello, Alice"
greet.call(person2); // "Hello, Bob"

const boundGreet = greet.bind(person1);
boundGreet(); // "Hello, Alice"

Summary Table

Context this refers to
Global Global object (window in browsers)
Function Global object (undefined in strict mode)
Method Object the method is called on
Constructor Newly created object
Arrow function Lexical context (where it's defined)
Event handler Element that received the event

Made with DeepSite LogoDeepSite - 🧬 Remix