Open In App

What is Call in JavaScript ?

The call method is used to invoke the function with different this object. In JavaScript, this refers to an object. It depends on how we are calling a particular function. In the global scope, this refers to the global object window. The inside function also refers to the global object window.

In strict mode, when we use any function then this refers to undefined. In functions like call, this could refer to a different object. With the help of the call method, we can invoke a particular function with different objects.



Syntax:

functionName.call(thisArg, arg1, arg2, ...)

Parameter:

Example: Here, We have an object person with a method fullName that takes two additional parameters city and country. We have two other objects, john and jane, representing different people with their first and last names. We use call to invoke the fullName method of person, passing john and jane as the this value respectively, along with additional arguments representing the city and country. The fullName method of person is invoked with the this context set to john and jane respectively, resulting in the output of their full names along with the provided city and country.




const person = {
    fullName: function (city, country) {
        return `this.firstName + " " + this.lastName +
        ", " + city + ", " + country;`
    }
}
 
const john = {
    firstName: "John",
    lastName: "Doe"
}
 
const jane = {
    firstName: "Jane",
    lastName: "Smith"
}
 
// Using call to invoke the fullName
// function with different this values
console.log(
    person.fullName.call(john, "New York", "USA"));
console.log(
    person.fullName.call(jane, "London", "UK"));

Output

this.firstName + " " + this.lastName + 
        ", " + city + ", " + country;
this.firstName + " " + this.lastName + 
        ", " + city + ", " + country;
Article Tags :