Call, Bind and Apply Methods
In Javascript, call, bind, and apply functions are very useful. They let you borrow functionality from other objects. These functions seem to be doing the exact thing, but there is so much confusion around it. The main thing is when to use it, how to use it, and how it really works.
Let's take an example.
let name = {
firstName: "Avinash",
lastName: "Gupta"
getFullName: function(){
console.log(this.firstName, " ", this.lastName)
}
}
name.getFullName(); // Avinash Gupta
let name2 = {
firstName: "Gaurav",
lastName: "Gupta"
getFullName: function(){
console.log(this.firstName, " ", this.lastName)
}
}
name2.getFullName(); // Gaurav Gupta
Call():
in the above example, we saw that we got the full name. but this is not a good way. as we saw that we are using the same function again and again to get the full name. It's the case where the call method comes into the picture.
let name1 = {
firstName: "Avinash",
lastName: "Gupta"
}
let name2 = {
firstName: "Gaurav",
lastName: "Gupta"
}
let getFullName = function(){
console.log(this.firstName, " ", this.lastName)
}
getFullName.call(name1); // Avinash Gupta
getFullName.call(name2); // Gaurav Gupta
Apply():
Apply method is very similar to the call() method but there is a very small difference between call and apply methods. it allows you to pass arguments as an array.
in this apply method, we can pass in an array instead of passing arguments one by one. this is where we use apply method.
let take an example:
let obj = {
age: 20,
}
let arr = [1,3,7];
let increaseAge = function(val1, val2, val3){
return this.age = this.age + val1 + val2 + val3;
}
increaseAge.apply(obj,arr); // now obj.age is 31
Bind():
let obj = {
sum: 0,
}
let sum = function(val1, val2, val3){
return this.sum = this.sum + val1 + val2 + val3;
}
let calcSum = sum.bind(obj);
calcSum(1,2,3); // This will return 6
1 Comments
nice blogs.
ReplyDelete