The difference between call / apply / bind

JavaScript is a dynamic language, and is flexible enough to let you do things like multiple inheritance. That’s when an object or a class can inherit characteristics from more than one parent. This can be done using one of these 3 methods: call / apply / bind. Read below or try it out yourself by cloning the code here.

So what’s the difference?

Call

Let’s say that we have an object called obj. It only has one property called things, which has a value of 3. Totally unrelated to this object, let’s also make a function called addThings.

let obj = {things: 3};
let addThings = function(a, b, c){
return this.things + a + b + c;
};

Notice this.things. Why does the addThings function mention that, when it doesn’t even have things? We need to pass it a context. We can do that with call. If we were to run this code:

console.log( addThings.call(obj, 1,4,6) );

It would return the number 14.

That’s because the first parameter that call takes, is the context we want “this” to refer to. We passed it obj, which does have the things property. After we pass the context, we can pass the arguments like we usually would. In this case we passed 1, 4, 6. So this line:

return this.things + a + b + c;

would be populated this way:

return 3 + 1 + 4 + 6;

Resulting in 14.

That’s what call does! Let’s look at the apply method.

Apply

apply is so similar to call that I don’t personally see its value. Pun intended.

I’ll explain it since you might need to know about it in a job interview. The main difference is the way we can pass arguments. We can pass them as an array. Clear the previous code from your mind and let’s start over.

let obj = {things: 3};
let addThings = function(a, b, c){
return this.things + a + b + c;
};
let arr = [1,4,6];
console.log( addThings.apply(obj, arr) );

Now let’s check out Bind.

Bind

let obj = {things: 3};
let addThings = function(a, b, c){
return this.things + a + b + c;
};
console.log( addThings.bind(obj, 1,4,6) );

We expected the number 14, but that didn’t work. Instead, it returned a function. Bind works by returning a copy of the function, but with a different context. We passed obj as the context, but we didn’t execute it. Let’s try that:

console.log( addThings.bind(obj, 1,4,6)() );

That worked! We can also pass the arguments like this:

console.log( addThings.bind(obj)(1,4,6) );

There you have it! Now you know about Call / Apply / Bind. Now go and apply it (lame)!

Happy coding,

Ivan