In JavaScript, the apply() method is used to invoke a function with a specified this value and an array or array-like object of arguments. It’s similar to the call() method but accepts arguments as an array. This method is particularly useful when the number of arguments is dynamic or when you want to pass an array of arguments to a function.
Syntax:
object.objectMethod.apply(objectInstance, arrayOfArguments)
Parameters: It takes two parameters:
- ObjectInstance: It is an object which we want to use explicitly
- Arguments: It is arguments that we want to pass to the calling function
Example: Here, apply() is used to invoke the greet() function with person as the this value and arguments provided in the args array.
Javascript
function greet(name, age) {
console.log(`Hello, ${name}! You are ${age} years old.`);
}
const person = { name: 'Alice' , age: 30 };
const args = [ 'Bob' , 25];
greet.apply(person, args);
|
Output
Hello, Bob! You are 25 years old.
|