Skip to main content
TOPIC 8 OF 8 · 2 MIN READ

this Keyword

The `this` keyword refers to the object that is executing the function. Its value depends on how the function is invoked.

Key concepts

this Keyword

Refers to the object that is executing the function. Its value depends on how the function is invoked.

Arrow Functions and this

Arrow functions do not have their own `this`; they inherit it from their enclosing scope.

Step by step

Call, Apply, Bind:

These methods explicitly set the value of `this`. `call` invokes the function with a specified `this` value and arguments provided individually. `apply` is similar to `call` but takes arguments as an array. `bind` creates a new function with a bound `this` value that can be called later.

Examples

Using this in Object Methods:

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

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

Arrow Functions and this:

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

user.greet(); // Hello, my name is undefined

call Method:

function greet(greeting) {
  console.log(`${greeting}, my name is ${this.name}`);
}

const user = { name: 'Alice' };
greet.call(user, 'Hello'); // Hello, my name is Alice

apply Method:

greet.apply(user, ['Hi']); // Hi, my name is Alice

bind Method:

const boundGreet = greet.bind(user);
boundGreet('Hey'); // Hey, my name is Alice

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus