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 asthiswhen callingfunc. IfthisArgisnullorundefined,thiswill be replaced with the global object in non-strict mode (or remainundefinedin strict mode).arg1,arg2, ... : Arguments passed to the functionfunc.
Main uses:
- Changing the call context: Allows explicitly specifying which object will be accessible via
thisinside the function. - Method borrowing: Enables using methods of one object for another.
- Inheritance emulation (pre-classes): In older JavaScript versions,
callcould 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 }