What is the difference between call, apply and bind?
All three of them exist for the same purpose, which is to control the this binding of a function. The difference between them is how they take the arguments and what they give back to you.
function greet(greeting, punctuation) {
return greeting + ', ' + this.name + punctuation;
}
const user = { name: 'Ada' };
// call: the arguments are listed one by one.
console.log(greet.call(user, 'Hello', '!')); // 'Hello, Ada!'
// apply: the arguments are listed as an array.
console.log(greet.apply(user, ['Hello', '?'])); // 'Hello, Ada?'
// bind: it returns a new function with the receiver already fixed.
const bound = greet.bind(user, 'Hello');
console.log(bound('!')); // 'Hello, Ada!'
console.log(bound.name); // 'bound Hello'
Call and apply both run the function straight away. The only difference between them is the shape of the argument list, and it does not matter much for a modern engine. Apply is the useful one when you already have the arguments inside an array, such as the result of a map over a list. Call is the useful one when you have a fixed set of arguments that you can simply write down.
Bind does not call anything at all. It returns a new function whose this is permanently set to the receiver that you gave it, and whose leading arguments are already applied. When you call that returned function later, the receiver is passed in automatically. That is exactly what makes bind the right tool for callbacks and for event listeners.
Two small details are worth knowing. The bound function has a name and a length that reflect the binding, and that is why the name shows the word bound in front of it. You can also call bind more than once, and each call adds another leading argument, which is how you build a partially applied function.