Home > Web Front-end > JS Tutorial > body text

Detailed explanation of several borrowing methods in JavaScript (graphic tutorial)

亚连
Release: 2018-05-19 16:11:17
Original
1343 people have browsed it

Let’s take a look at a detailed introduction to borrowing methods in JavaScript. Note: This article assumes that you have mastered the relevant knowledge of using call(), apply() and bind() and the differences between them. I hope this This article can let you know about the borrowing methods in JavaScript.

Preface

Through the call(), apply() and bind() methods, we can easily borrow methods from other objects without inheriting from these objects it.

Borrowing methods in JavaScript

In JavaScript, you can sometimes reuse functions or methods of other objects, and they do not have to be defined on the object itself or on its prototype. Through the call(), apply() and bind() methods, we can easily borrow methods from other objects without inheriting those objects. This is a common approach 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 an object. Array is an object suitable for traversing and converting ordered sequences. Its prototype has useful methods such as slice, join, push and pop.

A common example is that when the object and the array are both list-type data structures, the object can "borrow" methods from the array. The most commonly borrowed method 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');
Copy after login

The reason why borrowing methods is possible is that the call and apply methods allow functions to be called in different contexts, which also reuses existing functionality without having to inherit from other objects. A good way. In fact, arrays define many common methods in the prototype, such as join and filter:

// takes a string "abc" and produces "a|b|c
Array.prototype.join.call('abc', '|');
 
// takes a string and removes all non vowels
Array.prototype.filter.call('abcdefghijk', function(val) {
  return ['a', 'e', 'i', 'o', 'u'].indexOf(val) !== -1;
}).join('');
Copy after login

It can be seen that not only objects can borrow methods from arrays, Strings work too. 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 this way is verbose and can quickly get boring. A more efficient way is to use literals to achieve the same purpose.

Use literal borrowing method

Literal is a grammatical structure that follows JavaScript rules. MDN explains it this way:

In JavaScript, literals can be used to represent values. They are fixed values, either variables, or given literally in the script.
Literals can be abbreviated to prototype methods:

[].slice.call(arguments);
[].join.call('abc', '|');
''.toUpperCase.call(['lowercase', 'words', 'in', 'a', 'sentence']).split(',');
Copy after login

This does not look so verbose, but you must operate directly on [] and "" to borrow method, still a bit ugly. 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(',');
Copy after login

With references to borrowed methods, we can easily Use call() to call it, so you can reuse code. In line with the principle of reducing redundancy, let's see if we can borrow a method without writing call() or apply() every time it is called:

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(',');
Copy after login

As you can see, it is now possible to statically bind "borrowed" methods from different prototypes using Function.prototype.call.bind . But var slice = Function.prototype.call.bind(Array.prototype.slice) How does this sentence actually work?

Understanding Function.prototype.call.bind

Function.prototype.call.bind It may seem complicated at first, but understand how it works What works can be very beneficial.

Function.prototype.call is a reference that "calls" a function and sets its "this" value for use in the function.
Note that "bind" returns a new function with its "this" value. Therefore .bind(Array.prototype.slice) The "this" of the new function returned is always the Array.prototype.slice function.

To sum up, The new function will call the "call" function, and its "this" is the "slice" function. Calling slice() will point to the previously qualified method.

Custom object methods

Inheritance is great, but developers usually want to reuse some objects or modules Only used for general purpose functions. There is no need to use inheritance just for code reuse, as simple borrowing of methods will be complicated in most cases.

We only discussed borrowing native methods before, but borrowing any method is possible. For example, the following code can calculate the player score of the 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.375
console.log(&#39;Score: &#39; + score(player1));
 
// Score: 17
console.log(&#39;Score: &#39; + score(player2));
Copy after login

Although the above example is very blunt, it can be seen that, just like the native method, the user Defined methods can also be easily borrowed.

Summary

Call, bind, and apply can change the way a function is called, and are often used when borrowing functions. Most developers are familiar with borrowing native methods, but less often borrow custom methods.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Detailed discussion of the properties and methods of the built-in object Math in js (clear at a glance)

String method using JavaScript to implement pattern matching

javascript this detailed explanation (graphic tutorial)

The above is the detailed content of Detailed explanation of several borrowing methods in JavaScript (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template