What is the difference between call, apply and bind?
All three set this for a function. call runs it now with arguments listed one by one, apply runs it now with an array of arguments, and bind returns a new function with this fixed, to be run later.
Explain it simply
Think of lending your phone to a friend to make a call. call and apply mean: use my phone right now. The only difference is how you hand over the phone numbers: call takes them one by one, apply takes them as a single array (a for Apply, a for Array). bind is different: it gives you a copy of the function that is already tied to that phone, to use whenever you like.
So call and apply invoke, while bind returns a function.
Example
function intro(city, state) {
return this.name + " from " + city + ", " + state;
}
const person = { name: "Asha" };
console.log(intro.call(person, "Pune", "MH")); // Output: Asha from Pune, MH
console.log(intro.apply(person, ["Pune", "MH"])); // Output: Asha from Pune, MH
const introAsha = intro.bind(person, "Pune");
console.log(introAsha("MH")); // Output: Asha from Pune, MHThe bound function above already remembers person and the first argument, so only the state is left to pass.
What to say in the interview
"call and apply invoke the function immediately with a chosen this; call takes arguments separately and apply takes an array. bind does not invoke: it returns a new function with this permanently set, and optionally some arguments pre-filled. I use bind for callbacks and event handlers."
Common mistakes
- Forgetting that bind returns a function, so writing fn.bind(obj) without calling the result does nothing visible.