There are 3 types of function borrowing methods in JavaScript. They are call, apply and bind.
Let's take a look at how each of these methods work with examples.
- call
Syntax:
function.call(obj, arg1, arg2, arg3...);
The call method is capable of accepting multiple arguments in a comma separated fashion.
Let's take a look at the below example to understand how the call method works.
const obj1 = {
name: "Tejas",
printFavouriteFoodCombination: function(foodItem1, foodItem2) {
console.log(`My name is ${this.name}. I love eating ${foodItem1} and ${foodItem2}`);
}
}
const obj2 = {
name: "Tanay",
}
obj1.printFavouriteFoodCombination.call(obj2, "Bread", "Butter");
// "My name is Tanay. I love eating Bread with Butter"
- apply
Syntax:
function.apply(obj, [arg1, arg2, arg3...]);
The apply method is capable of accepting multiple arguments in the form of an array of arguments.
Let's take a look at the below example to understand how the apply method works.
const obj1 = {
name: "Tejas",
printFavouriteFoodCombination: function(foodItem1, foodItem2) {
console.log(`My name is ${this.name}. I love eating ${foodItem1} and ${foodItem2}`);
}
}
const obj2 = {
name: "Tanay",
}
obj1.printFavouriteFoodCombination.apply(obj2, ["Bread", "Butter"]);
// "My name is Tanay. I love eating Bread with Butter"
- bind
The bind method allows us to store the borrowed function inside a variable.
Syntax:
const newFunction = function.bind(obj, arg1, arg2, arg3...)
The bind method is capable of accepting multiple arguments in a comma separated fashion.
Let's take a look at the below example to understand how the bind method works.
const obj1 = {
name: "Tejas",
printFavouriteFoodCombination: function(foodItem1, foodItem2) {
console.log(`My name is ${this.name}. I love eating ${foodItem1} and ${foodItem2}`);
}
}
const obj2 = {
name: "Tanay",
}
const printFavFoodCombo = obj1.printFavouriteFoodCombination.bind(obj2, ["Bread", "Butter"]);
printFavFoodCombo();
// "My name is Tanay. I love eating Bread with Butter"
Hope you all liked this piece on the different function borrowing methods in JavaScript. Let me know in the comments down below if there's anything that can make this blog better. Cheers.