Call, Bind and Apply in JavaScript

Photo by Pankaj Patel on Unsplash

We know that functions are a special kind of object. Functions also get a couple of special methods which they inherit from the function constructor object. we will talk about the powerful call, apply and bind methods, which allow us to call a function and set this variable manually. let create an object:

let john = {
name:"John",
age: 26,
callFun:function(){
console.log(this.age);
}
}

on calling john.callFun(), the output will be 26.

john.callFun();
//Result is 26

Now let’s add another object here for someone called kim.

let kim = {
name:”Kim”,
age: 30
}

Now suppose that we want to use the callFun method for the Kim object, which does not have this callFun method, right? We can use the call method to do this. The first argument of the call method is always to set this variable.
So if we set this variable to kim then this variable will no longer be john.

john.callFun.call(kim);
//Result is 30

The call method allows us to set this variable here in the first argument, and we set it to “kim” because we wanted to use John’s callFun method. So that is the call method. There is a very similar method which is called the apply method, and the only difference is that this one accepts the arguments as an array, so that’s only two arguments, first this variable, and then an array where all the other arguments go.

john.callFun.apply(kim,[args1,args2]);
//Example represtation

The bind is very similar to the call method as well, so it also allows us to set this variable explicitly. However, the difference here is that bind doesn’t immediately call the function, but instead it generates a copy of the function
so that we can store it somewhere. And that can actually be extremely useful to create functions with preset arguments.

let kimBindCall = john.callFun.bind(kim);
kimBindCall();

Happy Reading!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store