Open In App

What is Call in JavaScript ?

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • functionName: The function to be called.
  • thisArg: The value to be passed as the this parameter when calling the function. If the function is a non-method function (i.e., a function declared at the global scope), thisArg is the global object (window in a browser, global in Node.js).
  • arg1, arg2, …: Arguments to be passed to the function individually.

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.

Javascript




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;

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads