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 AliceArrow Functions and this:
const user = {
name: 'Alice',
greet: () => {
console.log(`Hello, my name is ${this.name}`);
}
};
user.greet(); // Hello, my name is undefinedcall Method:
function greet(greeting) {
console.log(`${greeting}, my name is ${this.name}`);
}
const user = { name: 'Alice' };
greet.call(user, 'Hello'); // Hello, my name is Aliceapply Method:
greet.apply(user, ['Hi']); // Hi, my name is Alicebind Method:
const boundGreet = greet.bind(user);
boundGreet('Hey'); // Hey, my name is AliceStuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus