Junior — Middle
Explain the differences between the call and bind methods in JavaScript and how they affect the execution context of a function.
sobes.tech AI
Answer from AI
The call and bind methods in JavaScript are used to control the context (this) when calling a function, but they work differently:
callinvokes the function immediately, passing the context and arguments. For example:
function greet(greeting) {
console.log(greeting + ', ' + this.name);
}
const person = { name: 'Ivan' };
greet.call(person, 'Hello'); // Outputs: Hello, Ivan
bindreturns a new function with the bound context, which can be called later:
const boundGreet = greet.bind(person);
boundGreet('Good morning'); // Outputs: Good morning, Ivan
Thus, call executes the function immediately with the specified context, while bind creates a new function with a fixed context for later invocation.