Sobes.tech
Junior — Middle

What is the purpose of the call method in programming?

sobes.tech AI

Answer from AI

In Node.js, the call method is used to invoke a function with an explicit this context and to pass arguments individually.

Syntax:

func.call(thisArg, arg1, arg2, ...)
  • thisArg — the object to be used as this inside the function.
  • arg1, arg2, ... — the arguments passed to the function.

Example:

function greet(greeting) {
  console.log(greeting + ', ' + this.name);
}

const person = { name: 'Alice' };
greet.call(person, 'Hello'); // Outputs: Hello, Alice

call is useful when you need to invoke a function with a specific context, especially if the function is not a method of an object.