The call() method is a predefined JavaScript function method.
It can be used to invoke (call) a method with an owner object as an argument
(parameter). With call(), an object can use a method belonging to another
object.
This example shows how an object can "borrow" a method from another object. Here, the
person object has a method, but we use it on person1 and
person2.
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName: "Mim",
lastName: "Akter"
}
const person2 = {
firstName: "Redo",
lastName: "Hub"
}
// This will return "Mim Akter":
person.fullName.call(person1);
In JavaScript, the this keyword always refers to an object. In a method, it
refers to the object it belongs to. But with call(), you can
explicitly tell JavaScript which object this should refer
to.
The call() method can also accept arguments separately. After
the owner object, you can pass as many arguments as the function needs.
const person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
const person1 = {
firstName: "Mim",
lastName: "Akter"
}
person.fullName.call(person1, "Dhaka", "Bangladesh");
call() method takes arguments
separately, while the as-yet-unseen apply() method takes
arguments as an array.
call() allows an object to borrow methods from another
objectthis