


A brief analysis of the use and implementation of the bind() method in Javascript_javascript skills
Before discussing the bind() method, let’s look at a question:
var altwrite = document.write;
altwrite("hello");
//1. What’s wrong with the above code
//2. What is the correct operation
//3.How to implement the bind() method
For the above question, the answer is not too difficult. The main test point is the problem pointed by this. The altwrite() function changes the point of this to the global or window object, resulting in an illegal call exception during execution. The correct solution is to use bind () method:
altwrite.bind(document)("hello")
Of course, you can also use the call() method:
altwrite.call(document, "hello")
The focus of this article is to discuss the third issue, the implementation of the bind() method. Before starting to discuss the implementation of bind(), let’s first take a look at the use of the bind() method:
Binding function
The simplest use of bind() is to create a function so that the function has the same this value no matter how it is called. A common mistake is like the example above, taking the method out of the object and then calling it, hoping that this will point to the original object. If no special processing is done, the original object will generally be lost. Using the bind() method can solve this problem beautifully:
this.num = 9; var mymodule = { num: 81, getNum: function() { return this.num; } }; module.getNum(); // 81 var getNum = module.getNum; getNum(); // 9, 因为在这个例子中,"this"指向全局对象 // 创建一个'this'绑定到module的函数 var boundGetNum = getNum.bind(module); boundGetNum(); // 81
Partial Functions
Partial Functions are also called Partial Applications. Here is a definition of partial functions:
Partial application can be described as taking a function that accepts some number of arguments, binding values to one or more of those arguments, and returning a new function that only accepts the remaining, un-bound arguments.
This is a very good feature. Using bind() we set the predefined parameters of the function, and then pass in other parameters when calling:
function list() { return Array.prototype.slice.call(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3] // 预定义参数37 var leadingThirtysevenList = list.bind(undefined, 37); var list2 = leadingThirtysevenList(); // [37] var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
Use together with setTimeout
Generally, this of setTimeout() points to the window or global object. When you need this to point to a class instance when using a class method, you can use bind() to bind this to the callback function to manage the instance.
function Bloomer() { this.petalCount = Math.ceil(Math.random() * 12) + 1; } // 1秒后调用declare函数 Bloomer.prototype.bloom = function() { window.setTimeout(this.declare.bind(this), 1000); }; Bloomer.prototype.declare = function() { console.log('我有 ' + this.petalCount + ' 朵花瓣!'); };
Note: The above method can also be used for event handling functions and setInterval methods
Bind function as constructor
Bound functions are also suitable for using the new operator to construct instances of the target function. When using a bound function to construct an instance, note: this will be ignored, but the parameters passed in will still be available.
function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function() { return this.x + ',' + this.y; }; var p = new Point(1, 2); p.toString(); // '1,2' var emptyObj = {}; var YAxisPoint = Point.bind(emptyObj, 0/*x*/); // 实现中的例子不支持, // 原生bind支持: var YAxisPoint = Point.bind(null, 0/*x*/); var axisPoint = new YAxisPoint(5); axisPoint.toString(); // '0,5' axisPoint instanceof Point; // true axisPoint instanceof YAxisPoint; // true new Point(17, 42) instanceof YAxisPoint; // true
In the above example, Point and YAxisPoint share prototypes, so it is true when using the instanceof operator.
Shortcut
bind() can also create shortcuts for functions that require a specific this value.
For example, if you want to convert an array-like object into a real array, the possible examples are as follows:
var slice = Array.prototype.slice; // ... slice.call(arguments);
If you use bind(), the situation becomes simpler:
var unboundSlice = Array.prototype.slice; var slice = Function.prototype.call.bind(unboundSlice); // ... slice(arguments);
Achievement
It can be seen from the above sections that bind() has many usage scenarios, but the bind() function was only added in the fifth edition of ECMA-262; it may not run on all browsers. This requires us to implement the bind() function ourselves.
First we can simply implement the bind() method by specifying a scope for the target function:
Function.prototype.bind = function(context){ self = this; //保存this,即调用bind方法的目标函数 return function(){ return self.apply(context,arguments); }; };
Taking into account function currying, we can build a more robust bind():
Function.prototype.bind = function(context){ var args = Array.prototype.slice.call(arguments, 1), self = this; return function(){ var innerArgs = Array.prototype.slice.call(arguments); var finalArgs = args.concat(innerArgs); return self.apply(context,finalArgs); }; };
This time the bind() method can bind objects and also supports passing parameters during binding.
Continue, Javascript functions can also be used as constructors, so when the bound function is called in this way, the situation is more subtle, and the transfer of the prototype chain needs to be involved:
Function.prototype.bind = function(context){ var args = Array.prototype.slice(arguments, 1), F = function(){}, self = this, bound = function(){ var innerArgs = Array.prototype.slice.call(arguments); var finalArgs = args.concat(innerArgs); return self.apply((this instanceof F ? this : context), finalArgs); }; F.prototype = self.prototype; bound.prototype = new F(); return bound; };
This is the implementation of bind() in the book "JavaScript Web Application": by setting up a transit constructor F, the bound function and the function that calls bind() are on the same prototype chain, and the new operation is used operator calls the bound function, and the returned object can also use instanceof normally, so this is the most rigorous implementation of bind().
In order to support the bind() function in the browser, you only need to slightly modify the above function:
Function.prototype.bind = function (oThis) { if (typeof this !== "function") { throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply( this instanceof fNOP && oThis ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments)) ); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; };
The above brief analysis of the use and implementation of the bind() method in Javascript is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

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.

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

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.

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

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
