Here, first we will discuss why we need to require the call,apply & bind methods are required.So, first we will start with the problem statement with an example.
The example below creates an object with 3 properties, firstName, lastName, fullName.
const person = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
// This will return "John Doe":
person.fullName();
const person2 = {
firstName:"Kelvin",
lastName: "Saw",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
// This will return "Kelvin Saw":
person2.fullName();
You can see that the same function is being called multiple times, which causes duplication and is not reusable. There are three methods provided in JavaScript to solve this problem: Call,Apply & Bind.
The call() method is a predefined JavaScript method.
It can be used to invoke (call) a method with an object as an argument (parameter).
Example:
function showName() {
return this.firstName + " " + this.lastName;
}
const person = {
firstName: "John",
lastName: "Doe"
};
console.log(showName.call(person)); // Output: "John Doe"
const person2 = {
firstName: "Kelvin",
lastName: "Saw"
};
console.log(showName.call(person2)); // Output: "Kelvin Saw"
function showName(city,country) {
return this.firstName + " " + this.lastName + "," + city + "," + country; ;
}
const person = {
firstName: "John",
lastName: "Doe"
};
console.log(showName.call(person,"Ahmedabad","India")); // Output: "John Doe, Ahmedabad, India"
const person2 = {
firstName: "Kelvin",
lastName: "Saw"
};
console.log(showName.call(person2,"Maxico","US")); // Output: "Kelvin Saw, Maxico, US"
The apply method works similarly to call, but it takes an array of arguments instead of listing them individually.
Example:
function showName(city,country) {
return this.firstName + " " + this.lastName + "," + city + "," + country; ;
}
const person = {
firstName: "John",
lastName: "Doe"
};
console.log(showName.apply(person,["Ahmedabad","India"])); // Output: "John Doe, Ahmedabad, India"
const person2 = {
firstName: "Kelvin",
lastName: "Saw"
};
console.log(showName.apply(person2,["Maxico","US"])); // Output: "Kelvin Saw, Maxico, US"
The bind method returns a new function with a permanently bound this value. Unlike call and apply, bind does not execute the function immediately.
Example:
function greeting(greetingMsg) {
return greetingMsg + "," + this.firstName + " " + this.lastName;
}
const person = {
firstName: "John",
lastName: "Doe"
};
const bindMethod = greeting.bind(person,"Hello");
//When you need to retrieve the data, call the method like this:
console.log(bindMethod());
// Output: Hello, John Doe
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our NodeJS Expertise.