


Detailed explanation of several borrowing methods in JavaScript (graphic tutorial)
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');
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('');
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(',');
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(',');
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(',');
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('Score: ' + score(player1)); // Score: 17 console.log('Score: ' + score(player2));
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:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We
