In JavaScript, you can utilize methods from other objects to create functionality without inheriting all their properties and methods.
JavaScript offers two methods, call()
and apply()
, available for all function objects. These methods allow a function to be executed as if it were a method of another object. Here's an example:
var objA = {
name: "object A",
say: function(greet) {
alert(greet + ", " + this.name);
}
}
objA.say("Hi"); // Displays: Hi, object A
var objB = {
name: "object B"
}
/* The objB doesn't have say() method, but it can borrow it from objA */
objA.say.call(objB, "Hello"); // Displays: Hello, object B
call()
and apply()
MethodsThe syntax of the apply()
method is almost identical to call()
. The key difference is that call()
takes a list of arguments like call(thisObj, arg1, arg2, ...)
, whereas apply()
takes a single array of arguments like apply(thisObj, [argsArray])
.
Note the square brackets ([]
) denoting an array in the example below:
var objA = {
name: "object A",
say: function(greet) {
alert(greet + ", " + this.name);
}
}
objA.say("Hi"); // Displays: Hi, object A
var objB = {
name: "object B"
}
/* The objB doesn't have say() method, but it can borrow it from objA */
objA.say.apply(objB, ["Hello"]); // Displays: Hello, object B
The apply()
method also enables the use of built-in methods for performing tasks efficiently. One such example is utilizing Math.max()
or Math.min()
to determine the maximum or minimum value in an array, which would typically involve iterating through array elements.
As you might recall from earlier chapters, JavaScript arrays lack a max()
method, but Math provides one. Therefore, we can apply the Math.max()
method as shown below:
var numbers = [2, 5, 6, 4, 3, 7];
// Using Math.max apply
var max = Math.max.apply(null, numbers);
alert(max); // Outputs: 7
Note: In both call()
and apply()
, the first argument specifies the object on which the function is invoked. When null
is used as the first argument, it means the function is called without a specified object, affecting how the this
pointer behaves inside the function.
The new ES6 spread operator offers a more concise method to find the maximum or minimum value in an array, eliminating the need for the apply()
method. Here's an example:
var numbers = [2, 5, 6, 4, 3, 7];
// Using spread operator
var max = Math.max(...numbers);
alert(max); // Outputs: 7
However, both the spread operator (...
) and apply()
method may fail or produce incorrect results when dealing with arrays that contain a large number of elements (e.g., tens of thousands). In such scenarios, you can utilize Array.reduce()
to find the maximum or minimum value in a numeric array. This method iteratively compares each value to determine the maximum or minimum, as shown in the example below:
var numbers = [2, 5, 6, 4, 3, 7];
// Using reduce method
var max = numbers.reduce(function(a, b) {
return Math.max(a, b);
});
alert(max); // Outputs: 7