Junior — Middle
What is the difference between using call and bind methods when calling functions in JavaScript?
sobes.tech AI
Answer from AI
The call and bind methods in JavaScript are used to control the context (this) when calling functions, but they work differently:
-
callinvokes the function immediately, passing the context and arguments separately. -
bindreturns a new function with a bound context and, optionally, initial arguments, which can be called later.
Example:
function greet(greeting) {
console.log(greeting + ', ' + this.name);
}
const person = { name: 'Ivan' };
// call invokes the function immediately
greet.call(person, 'Hello'); // Outputs: Hello, Ivan
// bind returns a new function with a bound context
def greetPerson = greet.bind(person);
greetPerson('Good day'); // Outputs: Good day, Ivan
Thus, call is used for immediate invocation with the desired this, while bind is for creating a function with a fixed context that can be called later.