Using the apply() method, you can write a function that can be applied to different objects by passing different this values.
The apply() method is similar to the call() method (as discussed in the previous chapter).
In this example, the fullName method of person is applied to person1.
const person = { fullName: function() { return this.firstName + ” “ + this.lastName; } } const person1 = { firstName: “Mary”, lastName: “Doe” } // This will return “Mary Doe”: person.fullName.apply(person1); |
The difference is:
The call() method accepts arguments individually.
The apply() method accepts arguments as an array.
The apply() method is useful when you want to pass an array as arguments instead of a separate list of arguments. |
The apply() method accepts arguments as an array.
const person = { fullName: function(city, country) { return this.firstName + ” “ + this.lastName + “,” + city + “,” + country; } } const person1 = { firstName:“John”, lastName: “Doe” } person.fullName.apply(person1, [“Oslo”, “Norway”]); |
In comparison to the call() method:
const person = { fullName: function(city, country) { return this.firstName + ” “ + this.lastName + “,” + city + “,” + country; } } const person1 = { firstName:“John”, lastName: “Doe” } person.fullName.call(person1, “Oslo”, “Norway”); |
You can find the largest number in a list of numbers using the Math.max() method.
Math.max(1,2,3); // Will return 3 |
Since JavaScript arrays do not have a max() method, you can use the Math.max() method with the array elements.
Math.max.apply(null, [1,2,3]); // Will also return 3 |
The first argument (null) is irrelevant in this example, as it is not used.
These examples will produce the same result:
Math.max.apply(Math, [1,2,3]); // Will also return 3 |
Math.max.apply(” “, [1,2,3]); // Will also return 3 |
Math.max.apply(0, [1,2,3]); // Will also return 3 |
In JavaScript strict mode, if the first argument of the apply() method is not an object, it is treated as undefined and does not become the owner of the invoked function. In non-strict mode, it becomes the global object.