Apply() method is used to write method on different objects. It is similar to the call() method with minor difference. The call() method takes arguments separately. The apply() method takes arguments as an array.
apply() syntax:
func.apply(thisArg, argsArray)
The apply() methos takes two parameters,
thisArg : the value of this which is provided by calling the function func.
argsArray (optional) — An array containing the arguments to the function.
The apply method calls a function with the passed this keyword value and arguments provided in the form of an array.
const name = {
firstName: 'Jane',
lastName: 'Doe'
}
function greet(wish, message) {
return `${this.firstname}, ${wish}, ${message}`;
}
let res = greet.apply(name, ['good morning', 'how are you?']);
console.log(res);
// output :
// Jane, good morning, how are you?
another example for apply ()
const car = {
name:'Audi',
description() {
return `The ${this.name} is of ${this.color} color`
}
}
const bike = {
name: 'Duke',
color: 'Black'
}
let result = car.description.apply(bike);
console.log(result)
//Output :
// The Duke is of Black color
Bike is borrowing description() method from car using apply().
If you liked my blog, please do follow me on Rhea RB
Thank you for Reading ! Happy Coding !!!