- What is
apply?
apply() method is a function that allows you to call another function with a specified this value and arguments provided as an array.
- Syntax
function.apply(thisArg, argsArray);
thisArg: The value to be used as this when calling the function.
argsArray: An array (or array-like object) containing the arguments to be passed to the function.
- Example 1:
function greet(greeting) {
console.log(greeting + ", " + this.name);
}
const person = {name: "Alice"};
greet.apply(person, ["Hello"]);
- Example 2:
var obj = { name: "Chaitanya" };
function sayHello(age, profession) {
return "Hello " + this.name + " is " + age + " and is an " + profession;
}
console.log(sayHello.apply(obj, [22, "Software Engineer"]));