Sobes.tech
Junior

What does the call function do in JavaScript?

sobes.tech AI

Answer from AI

The call function in JavaScript invokes the function it is applied to, setting a specific this value and passing arguments individually.

General syntax:

func.call(thisArg, arg1, arg2, ...);
  • thisArg: The value to be used as this when calling func. If thisArg is null or undefined, this will be replaced with the global object in non-strict mode (or remain undefined in strict mode).
  • arg1, arg2, ... : Arguments passed to the function func.

Main uses:

  • Changing the call context: Allows explicitly specifying which object will be accessible via this inside the function.
  • Method borrowing: Enables using methods of one object for another.
  • Inheritance emulation (pre-classes): In older JavaScript versions, call could be used to invoke a parent constructor with the context of a child object.

Example of changing context:

function greet() {
  console.log(`Hello, ${this.name}!`);
}

const person = { name: 'Peter' };

greet.call(person); // Outputs: Hello, Peter!

Example of method borrowing:

const numbers = [1, 2, 3];

// Using the array method splice on an array-like object
const arrayLike = { 0: 'a', 1: 'b', length: 2 };

Array.prototype.splice.call(arrayLike, 0, 1);

console.log(arrayLike); // Outputs: { 0: 'b', length: 1 }
What does the call function do in JavaScript? — Node.js - sobes.tech