Preface
Through the call(), apply() and bind() methods, we can easily borrow methods from other objects without inheriting it from these objects.
Borrowing methods in JavaScript
In JavaScript, functions or methods of other objects can sometimes be reused, not necessarily defined on the object itself or on the prototype. Through the call(), apply() and bind() methods, we can easily borrow methods from other objects without inheriting them. This is a common method used by professional JavaScript developers.
Prototype method
In JavaScript, except for unchangeable primitive data types, such as string, number, and boolean, almost all data is objects. Array is an object suitable for traversing and converting ordered sequences. Its prototype has easy-to-use methods such as slice, join, push and pop.
A common example is that when both objects and arrays are data structures of list type, objects can "borrow" methods from arrays. The most common method to borrow is Array.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');Borrowing methods work because the call and apply methods allow calling functions in different contexts, which is also a good way to reuse existing functions without having to inherit other objects. In fact, arrays define many common methods in prototypes, such as join and filter:
// take a string "abc" and produces "a|b|cArray.prototype.join.call('abc', '|'); // take a string and removes all non vowelsArray.prototype.filter.call('abcdefghijk', function(val) { return ['a', 'e', 'i', 'o', 'u'].indexOf(val) !== -1;}).join(''); It can be seen that not only objects can borrow array methods, but also strings. But because generic methods are defined on the prototype, you must use String.prototype or Array.prototype every time you want to borrow a method. Writing like this is very verbose and will soon become annoying. A more efficient way is to use literals to achieve the same purpose.
Using literal borrowing methods
Literals are a syntax structure that follows JavaScript rules, MDN explains it like this:
In JavaScript, using literals can represent values. They are fixed values, either variables, or given literally in the script.
Literals can be abbreviated as prototype:
[].slice.call(arguments);[].join.call('abc', '|');''.toUpperCase.call(['lowercase', 'words', 'in', 'a', 'sentence']).split(',');This doesn't seem so verbose, but it's still a bit ugly to have to operate directly on [] and "" to borrow the method. You can use variables to save references to literals and methods, which makes it 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 references to borrow methods, we can easily call it with call(), which can also reuse the code. Adhering to the principle of reducing redundancy, let's see if we can borrow methods without having to write call() or apply() every time we 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 now use Function.prototype.call.bind to statically bind the "borrowed" method from different prototypes. But how does the sentence var slice = Function.prototype.call.bind(Array.prototype.slice) actually work?
Understand Function.prototype.call.bind
Function.prototype.call.bind may seem a bit complicated at first glance, but it can be very helpful to understand how it works.
Function.prototype.call is a reference that "call" a function and will set its "this" value for use in a function.
Note that "bind" returns a new function with its "this" value. Therefore, the "this" of the new function returned by .bind(Array.prototype.slice) is always the Array.prototype.slice function.
To sum up, the new function calls the "call" function, and its "this" is the "slice" function. Calling slice() will point to the previously qualified method.
Methods to customize objects
Inheritance is great, but developers usually use it when they want to reuse some common features between objects or modules. There is no need to use inheritance just for code reuse, because simple borrowing methods can be complicated in most cases.
We only discussed borrowing native methods before, but borrowing any method is OK. For example, the following code can calculate the player score of points game:
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 native methods, user-defined methods can be easily borrowed.
Summarize
Call, bind, and apply can change the way functions are called and are often used when borrowing functions. Most developers are familiar with borrowing native methods, but rarely borrowing custom methods.
In recent years, JavaScript's functional programming has developed well. How to use Function.prototype.call.bind to borrow the method more convenient? It is estimated that such topics will become more and more common.
The above is the summary of the borrowing methods in JavaScript. I hope it will be helpful for everyone to understand the borrowing methods in JavaScript.