


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!

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
