HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Function Call

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.


Method Borrowing

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);

Explicitly Setting 'this'

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 with Arguments

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");
Difference: The call() method takes arguments separately, while the as-yet-unseen apply() method takes arguments as an array.

Key Points to Remember

  • call() allows an object to borrow methods from another object
  • It explicitly sets the value of this
  • The first argument is the owner object
  • Additional arguments are passed one by one (separated by commas)
  • It is very useful for writing standardized code that can be applied to different data objects