The apply() method is very similar to the call()
method. It allows an object to use a method belonging to another object, but with one major
difference: apply() takes arguments as an array.
While both methods explicitly set the value of this, they handle additional
arguments differently:
call() takes arguments separately
(comma-separated).apply() takes arguments as an
array.const person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
const person1 = {
firstName: "Mim",
lastName: "Akter"
}
// apply() takes arguments in square brackets (array)
person.fullName.apply(person1, ["Oslo", "Norway"]);
The apply() method is particularly useful when you want to use built-in
functions like Math.max() on an array of numbers.
Normally, Math.max() only accepts individual numbers.
const numbers = [5, 6, 2, 3, 7];
// Math.max(5, 6, 2, 3, 7) would be hard with a dynamic array
let max = Math.max.apply(null, numbers);
console.log(max); // 7
null as the first
argument because Math.max does not depend on any specific object for its
this value.
apply() invokes a function with a given
this value[]call() when your data is already in an array
(...) is
often used instead of `apply()`.