Let's talk about several borrow methods in JavaScript.
Preface
Using call (), apply (), and bind () methods, we can easily borrow methods from other objects without inheriting them from them.
Borrow methods in JavaScript
In JavaScript, functions or methods of other objects can be reused, not necessarily defined on the object itself or prototype. The call (), apply (), and bind () methods allow us to easily borrow methods from other objects without inheriting them. This is a common method for professional JavaScript developers.
Prototype Method
In JavaScript, almost all data except the unchangeable original data types such as string, number, and boolean are objects. Array is an object that can be used to traverse and convert an ordered series. Its prototype includes slice, join, push, pop, and other useful methods.
A common example is that when the object and array are both list-type data structures, the object can be "borrowed" from the array. The most common method to borrow isArray.prototype.slice
.
function myFunc() { // error, arguments is an array like object, not a real array arguments.sort(); // "borrow" the Array method slice from its prototype, which takes an array like object (key:value) // and returns a real array var args = Array.prototype.slice.call(arguments); // args is now a real Array, so can use the sort() method from Array args.sort(); } myFunc('bananas', 'cherries', 'apples');
The borrow method is feasible because the call and apply methods allow function calling in different contexts. This is also a good way to reuse existing functions without inheriting other objects. In fact, arrays define many common methods in the prototype, such as join and filter:
// takes a string "abc" and produces "a|b|cArray.prototype.join.call('abc', '|'); // takes a string and removes all non vowelsArray.prototype.filter.call('abcdefghijk', function(val) { return ['a', 'e', 'i', 'o', 'u'].indexOf(val) !== -1;}).join('');
We can see that not only can an object borrow an array, but also a string. However, because generic methods are defined on the prototype, they must be used each time they want to borrow a method.String.prototype
OrArray.prototype
. It will soon be annoying. A more effective way is to use the literal to achieve the same purpose.
Use the literal borrow Method
Literal is a syntax structure that follows JavaScript rules. MDN explains this as follows:
In JavaScript, a literal can represent a value. They are fixed values, not variables, but are given literally in the script.
The literal can be abbreviated as the prototype:
[].slice.call(arguments);[].join.call('abc', '|');''.toUpperCase.call(['lowercase', 'words', 'in', 'a', 'sentence']).split(',');
This seems not so long, but it is still a bit ugly to operate on [] and "" directly to borrow methods. You can use variables to save references to the literal and method, which is easier to write:
var slice = [].slice;slice.call(arguments);var join = [].join;join.call('abc', '|'); var toUpperCase = ''.toUpperCase;toUpperCase.call(['lowercase', 'words', 'in', 'a', 'sentence']).split(',');
With reference to the borrow method, we can use call () to call it easily, so that code can be reused. Adhering to the principle of reducing redundancy, let's see if we can borrow a method, but we don't need to write call () or apply () for each call ():
var slice = Function.prototype.call.bind(Array.prototype.slice);slice(arguments); var join = Function.prototype.call.bind(Array.prototype.join);join('abc', '|'); var toUpperCase = Function.prototype.call.bind(String.prototype.toUpperCase);toUpperCase(['lowercase', 'words', 'in', 'a', 'sentence']).split(',');
As you can see, you can useFunction.prototype.call.bind
To statically bind the "borrowed" method from different prototypes. Howevervar slice = Function.prototype.call.bind(Array.prototype.slice)
How does this sentence actually work?
Understanding Function. prototype. call. bind
Function.prototype.call.bind
It seems complicated at first glance, but it is very helpful to understand how it works.
Function.prototype.call
Is a reference. You can call the function and set its "this" value to use it in the function.
Note that "bind" returns a new function with its "this" value. Therefore.bind(Array.prototype.slice)
The "this" of the returned new function is always the Array. prototype. slice function.
To sum up,The new function calls the "call" function, and its "this" is the "slice" function. When slice () is called, it points to the previously defined method.
Custom object Method
Inheritance is great, but developers usually use it when they want to reuse some objects or common functions between modules. There is no need to use inheritance only for code reuse, because in most cases, simple borrow methods are complicated.
Previously, we only discussed the use of native methods, but any method can be used. For example, the following code can calculate the score of a point game player:
var scoreCalculator = { getSum: function(results) { var score = 0; for (var i = 0, len = results.length; i < len; i++) { score = score + results[i]; } return score; }, getScore: function() { return scoreCalculator.getSum(this.results) / this.handicap; }};var player1 = { results: [69, 50, 76], handicap: 8}; var player2 = { results: [23, 4, 58], handicap: 5}; var score = Function.prototype.call.bind(scoreCalculator.getScore); // Score: 24.375console.log('Score: ' + score(player1)); // Score: 17console.log('Score: ' + score(player2));
Although the above example is very blunt, it can be seen that, just like the native method, user-defined methods can also be easily borrowed.
Summary
Call, bind, and apply can change the function Call method and are often used when a function is borrowed. Most developers are familiar with using native methods, but seldom use custom methods.
In recent years, functional programming in JavaScript has developed well. How to use Function. prototype. call. bind to borrow methods is easier? It is estimated that such a topic will become more and more common.
The above is all the summary of the borrow method in JavaScript. I hope you can understand the borrow method in JavaScript.