Middle
How can you set the context of a function? What is the difference between call, apply, and bind?
sobes.tech AI
Answer from AI
In JavaScript, the function context (the value of this) can be explicitly set using the call, apply, and bind methods.
callinvokes the function immediately, passing the context and arguments separately.applyinvokes the function immediately, passing the context and arguments as an array.bindreturns a new function with the bound context, which can be called later.
Example:
function greet(greeting) {
console.log(`${greeting}, my name is ${this.name}`);
}
const person = { name: 'Ivan' };
greet.call(person, 'Hello'); // Hello, my name is Ivan
greet.apply(person, ['Good day']); // Good day, my name is Ivan
const boundGreet = greet.bind(person);
boundGreet('Hi'); // Hi, my name is Ivan
Thus, call and apply invoke the function immediately with the specified context, while bind creates a new function with the bound context for later invocation.