#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
•Question 7 of 50hard

How does the "this" keyword work in JavaScript?

Understanding this binding in different contexts.

What You'll Learn

  • How this is determined
  • Different binding rules
  • Arrow functions and this

The "this" Keyword

this refers to the object that is executing the current function. Its value depends on how the function is called.

Binding Rules

Contextthis Value
Globalwindow (browser) / global (Node)
Object methodThe object
ConstructorNew instance
Arrow functionInherited from parent
Event handlerElement that received event

Examples

code.jsJavaScript
// Object method
const obj = {
  name: 'John',
  greet() {
    console.log(this.name); // 'John'
  }
};

// Arrow function (inherits this)
const obj2 = {
  name: 'Jane',
  greet: () => {
    console.log(this.name); // undefined (inherits from parent)
  }
};

// Explicit binding
function sayName() {
  console.log(this.name);
}
sayName.call({ name: 'Bob' }); // 'Bob'
sayName.apply({ name: 'Alice' }); // 'Alice'
const bound = sayName.bind({ name: 'Charlie' });
bound(); // 'Charlie'