Let's directly dive into code and understand the call(), apply() and bind() method:
let info={
name: "Sanket",
state: "Maharashtra",
getInfo: function (){
console.log(this.name + " from "+ this.state);
}
}
let info1={
name: "Ankur",
state: "Gujarat"
}
call()
There is a concept in JavaScript known as Function borrowing where we can borrow the method from another object. if we want to use getInfo() Method in the info1 object we use the call() method.
The first argument in the call() method is the object we wanna refer to keyword this.
info.getInfo.call(info1); // Ankur from Gujarat
call() method directly call the function.
The good way to write the generic method is outside of the object so that any object can refer to it.
let getInfo = function (){
console.log(this.name + " from "+ this.state);
}
let info={
name: "Sanket",
state: "Maharashtra"
}
let info1={
name: "Ankur",
state: "Gujarat"
}
Now we can access this function as:
getInfo.call(info); // Sanket from Maharashtra
getInfo.call(info1); // Ankur from Gujarat
If the function receives any parameters we can pass it in the call() method along the obj we wanna refer this to by comma separation.
let getInfo = function (country){
console.log(this.name + " from "+ this.state + ", "+ country);
}
let info={
name: "Sanket",
state: "Maharashtra"
}
let info1={
name: "Lucifer",
state: "LA"
}
Now we can use the call() method as
getInfo.call(info, "India"); //Sanket from Maharashtra, India
getInfo.call(info1, "USA"); // Lucifer from LA, USA
apply()
apply() method is the same as the call() method but the only difference is we pass arguments in the list inside apply() method.
getInfo.apply(info, ["India"]);//Sanket from Maharashtra, India
getInfo.apply(info1, ["USA"]); // Lucifer from LA, USA
If there are multiple arguments you can use a comma separation.
bind()
bind() method is also the same as the call() method. the only difference is instead of directly calling the function like the call() method bind() method returns a function which we can invoke later in our program.
let personalInfo = getInfo.bind(info, "India");
// ...
personalInfo(); //Sanket from Maharashtra, India
That's it for this article!