What are the differences between .bind(), .call(), and .apply() ?

.bind(), .call(), and .apply() are some important JavaScript concepts.

What are they?

bind(), call(), and apply() are used to change the reference of ‘this’ for a given function.

Why do we use it?

It’s good to borrow a function and change the reference to a new object.

Definition

func.call(): calls the given function and allows you to pass in an object with arguments
func.apply(): same as call except the arguments you pass must be an array of arguments
func.bind(): returns a new function and allows you to pass in an object with arguments in an array or any number of arguments

Example

First, let’s set up bubble tea objects and a blend function

var appleBubbleTea = { fruit: 'apple', sugar: '50%', pearls: 'boba'};
var lemonTea = { fruit: 'lemon', sugar: '20%', pearls: 'jelly'};
function blend(customerName) {
console.log('Blending ' + this.fruit + ' with ' + this.pearls + ' for ' + customerName);
}

A customer wants to order a cup of bubble tea and we are going to make it.

Using Call

blend.call(appleBubbleTea, 'Kathy'); 
//Blending apple with boba for Kathy
blend.call(lemonTea, 'Mike'); 
//Blending apple with boba for Mike

Using Apply

blend.apply(appleBubbleTea, [‘Kathy’]);
//Blending apple with boba for Kathy

blend.apply(lemonTea, [‘Mike’]);
//Blending apple with boba for Mike

Using Bind

var mixingAppleBubbleTea = blend.bind(appleBubbleTea, 'Kathy'); 
var mixingLemonTea = blend.bind(lemonTea, ['Mike']);
mixingAppleBubbleTea(); //Blending apple with boba for Kathy
mixingLemonTea(); //Blending lemon with jelly for Mike

Live Code: https://jsbin.com/wipufo/edit?js,console

What’s going on?

You notice that they all give the same results. .call() and .apply() are pretty much the same except .call() takes a comma separated arguments whereas .apply() takes an array of arguments. To help myself remember, call takes comma-separated arguments and apply takes an array of arguments. They also execute immediately.

.bind() does not execute immediately, and returns a new function. If you want to execute it immediately, you will need to revoke the new function. It also takes both comma-separated arguments and an array of arguments.