Arrow functions don't have their own this - they inherit it from the surrounding lexical context.
const obj = {
name: 'My Object',
regularMethod: function() {
console.log(this); // obj
const arrowInside = () => {
console.log(this); // obj (inherited from regularMethod)
};
arrowInside();
},
arrowMethod: () => {
console.log(this); // window (inherited from global scope)
}
};
obj.regularMethod();
obj.arrowMethod();
const obj = {
name: 'My Object',
regularMethod: function() {
console.log(this); // obj
const arrowInside = () => {
console.log(this); // obj (inherited from regularMethod)
};
arrowInside();
},
arrowMethod: () => {
console.log(this); // window (inherited from global scope)
}
};
obj.regularMethod();
obj.arrowMethod();
Explicit Binding
You can explicitly set this using:
call(): Set this and call the function immediately with individual arguments
apply(): Like call(), but takes arguments as an array. this binding is limited for the function call.
bind(): Returns a new function with this permanently bound. Unlike call and apply, bind doesnt invoke the function immediately. Additionally the this binding is permanent. Once a function is created with bind(), you cannot change its this context using call() or apply() - the binding is permanent for that new function.
function greet() {
console.log(`Hello, ${this.name}`);
}
const person = { name: 'Alice' };
// call() and apply() immediately invoke the function
greet.call(person); // Hello, Alice
greet.apply(person); // Hello, Alice
// bind() creates a new function with bound this
const boundGreet = greet.bind(person);
boundGreet(); // Hello, Alice
function greet() {
console.log(`Hello, ${this.name}`);
}
const person = { name: 'Alice' };
// call() and apply() immediately invoke the function