Javascript Function call()

The JavaScript Function call() method calls a function with a given this value and arguments provided individually.

The syntax of the call() method is:

func.call(thisArg, arg1, ... argN)

Here, func is a function.


call() Parameters

The call() method takes in:

  • thisArg - The value of this provided for the call to func.
  • arg1, ... argN (optional) - Arguments for the function.

Return value from call()

  • Returns the result of calling the function with the specified this value and arguments.

By using call(), we can use the functions belonging to one object to be assigned and called for a different object.

Example 1: Using call()

function greet() {
  const string = `My name is ${this.firstName} ${this.secondName}. I am ${this.age} years old.`;
  console.log(string);
}

const human = {
  firstName: "Judah",
  lastName: "Parker",
  age: 26,
};

greet.call(human); // My name is Judah undefined. I am 26 years old.

Output

My name is Judah undefined. I am 26 years old.

Example 2: Using call() to chain constructors

function Animal(name, age) {
  this.name = name;
  this.age = age;
}

function Horse(name, age) {
  Animal.call(this, name, age);
  this.sound = "Neigh";
}

function Snake(name, age) {
  Animal.call(this, name, age);
  this.sound = "Hiss";
}

const snake1 = new Snake("Harry", 5);
console.log(snake1.name, snake1.age, snake1.sound);

const horse1 = new Horse("Arnold", 8);
console.log(horse1.name, horse1.age, horse1.sound);

Output

Harry 5 Hiss
Arnold 8 Neigh

Note: The difference between call() and apply() is that call() accepts an argument list, while apply() accepts a single array of arguments.


Recommended Reading: JavaScript Function apply()