JavaScript Borrowing Methods. Here’s What You Need To Know
Posted by TotalDC
Lets continue our JavaScript series by learning about JavaScript Borrowing Methods – how to borrow functionality from existing objects in JavaScript.
In JavaScript you can borrow methods from other objects to build some functionality without the need to inherit all their properties and methods.
JavaScript provides two methods for all function objects – call() and apply(). These methods allows function to be invoked as if it were a method of another object. Here’s an example for you:
let objA = {
name: "object A",
say: function(greet) {
console.log(greet + ", " + this.name);
}
}
objA.say("Hi"); // Result: Hi, object A
let objB = {
name: "object B"
}
/* The objB doesn't have say() method, but it can borrow it from objA */
objA.say.call(objB, "Hello"); // Result: Hello, object B
Difference Between call() and apply() Methods In JavaScript
Actually the syntax of these two methods is identical, the only difference is that call() method takes a list of arguments – call(thisObj, arg1, arg2, …) and apply() method takes a single array of arguments – apply(thisObj, [argsArray]). Here’s an Example:
let objA = {
name: "object A",
say: function(greet) {
alert(greet + ", " + this.name);
}
}
objA.say("Hi"); // Result: Hi, object A
let objB = {
name: "object B"
}
/* The objB doesn't have say() method, but it can borrow it from objA */
objA.say.apply(objB, ["Hello"]); // Result: Hello, object B
Using Built-in Methods In JavaScript
The apply() method also allows you to use built-in methods for performing some tasks quickly and easily. One example is using the Math.max()/Math.min() to find out the maximum or minimum value in an array, that would otherwise require looping over the array values.
As you already know from the previous chapters JavaScript arrays do not have a max() method, but Math has, so we can apply the Math.max() method, like this:
let numbers = [2, 5, 6, 4, 3, 7];
// Using Math.max apply
let max = Math.max.apply(null, numbers);
console.log(max); // Result: 7
The ES6 spread operator provides a shorter way to obtain the maximum or minimum value from an array without using the apply() method. Here’s an example:
let numbers = [2, 5, 6, 4, 3, 7];
// Using spread operator
let max = Math.max(...numbers);
console.log(max); // Result: 7
Both spread (…) and apply() will either fail or return the incorrect result if the array has too many elements. In that case you can use the Array.reduce() to find the maximum or minimum value in a numeric array, by comparing each value. Here’s how it looks:
let numbers = [2, 5, 6, 4, 3, 7];
// Using reduce method
let max = numbers.reduce(function(a, b) {
return Math.max(a, b);
});
console.log(max); // Result: 7
Leave a Reply