Discuss the bind() function in javascript
Understand the bind() function in javascript
Share:
The bind() method will create a new function, When this new function is called, its this value is the first parameter passed to bind(), and its parameters are the other parameters of bind() and its original parameters.
The syntax is like this:
fun.bind(thisArg[, arg1[, arg2[, ...]]])
thisArg When the bound function is called, this parameter will be used as the this pointer of the original function when it is run. This parameter has no effect when calling the bound function using the new operator.
arg1, arg2, … (optional) When the bound function is called, these parameters plus the parameters of the bound function itself will be used as the parameters of the original function when running in order.
Parameters
The first parameter of bind will be used as this pointer when the original function is running, not to mention; the second starting parameter is optional , when the bound function is called, these parameters plus the parameters of the bound function itself will be used as the parameters of the original function when running in order. How to understand?
function fn(a, b, c) { return a + b + c; } var _fn = fn.bind(null, 10); var ans = _fn(20, 30); // 60
The fn function requires three parameters. The _fn function uses 10 as the default first parameter, so you only need to pass in two parameters. If you accidentally pass in three parameters, don’t worry. Only the first two will be taken.
function fn(a, b, c) { return a + b + c; } var _fn = fn.bind(null, 10); var ans = _fn(20, 30, 40); // 60
What’s the use of this? If the first few parameters of some functions have been "defaulted", we can use bind to return a new function. In other words, bind() enables a function to have preset initial parameters. These parameters (if any) follow this as the second parameter of bind(), and they will then be inserted at the beginning of the target function's parameter list, and the parameters passed to the bound function will follow them. .
function list() { return Array.prototype.slice.call(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3] // Create a function with a preset leading argument var leadingThirtysevenList = list.bind(undefined, 37); var list2 = leadingThirtysevenList(); // [37] var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
new
The result returned by bind is still a function. If it is a function, it can be called by the new operator. So what about the result? The specification makes it very clear that when the new operator is used to call a bound function, the first parameter of bind is invalid.
function Person(name, age) { this.name = name; this.age = age; } var _Person = Person.bind({}); var p = new _Person('hanzichi', 30); // Person {name: "hanzichi", age: 30}
Generally we will not use it this way, but if you want to write a bind polyfill (http://caniuse.com/#search=bind), you still need to consider using new to call it.
We can also set default values (refer to the previous section), and the parameters originally provided will still be prepended to the constructor call.
function Person(name, age) { this.name = name; this.age = age; } var _Person = Person.bind(null, 'hanzichi'); var p = new _Person(30); // Person {name: "hanzichi", age: 30}
With setTimeout
When is it easy to lose this pointer? Well, setTimeout is a scene, and it is easy to point this to the window. Of course, the same is true for setInterval. When using an object's methods, which require this to refer to the object, you may need to explicitly bind this to the callback function in order to continue using the object.
var canvas = { render: function() { this.update(); this.draw(); }, update: function() { // ... }, draw: function() { // ... } }; window.setInterval(canvas.render, 1000 / 60);
We often encounter similar problems when using canvas to write special effects or make games. There is a problem with the above code. This in the render method is actually pointed to the window! We can use bind to explicitly bind this to the callback function so that we can continue to use the object.
window.setInterval(canvas.render.bind(canvas), 1000);
A similar situation is the event monitoring of dom. If you are not careful, this may be pointed to the dom element. You can refer to this part of the code written when working on bigrender before https://github.com/hanzichi/hanzichi.github.io/blob/master/2016/bigrender/js/bigrender.js#L179-L184.
#tip
bind can also do some interesting things.
Generally speaking, to convert an array-like array to an array, we will use slice (ie9- does not support it). Refer to #14
var slice = Array.prototype.slice; // slice.apply(arguments); // slice(arguments, 1); bind 能让调用变的更加简单。 // same as "slice" in the previous example var unboundSlice = Array.prototype.slice; var slice = Function.prototype.call.bind(unboundSlice); // ... slice(arguments); // slice(arguments, 1);
for another similar example. For example, if we want to add events to multiple nodes, of course there is no problem with the for loop. We can also "plagiarize" the forEach method:
Array.prototype.forEach.call(document.querySelectorAll('input[type="button"]'), function(el){ el.addEventListener('click', fn); });
Further, we can use bind to encapsulate the function better:
var unboundForEach = Array.prototype.forEach , forEach = Function.prototype.call.bind(unboundForEach); forEach(document.querySelectorAll('input[type="button"]'), function (el) { el.addEventListener('click', fn); });
Similarly, we can change x.y(z) into the form of y(x,z):
var obj = { num: 10, getCount: function() { return this.num; } }; var unboundBind = Function.prototype.bind , bind = Function.prototype.call.bind(unboundBind); var getCount = bind(obj.getCount, obj); console.log(getCount()); // 10
Give another chestnut. Printing 1-5 on the console every second seems to be a classic problem when examining closures.
for(var i = 1; i <= 5; i++) { !function(i) { setTimeout(function() { console.log(i); }, i * 1000); }(i); }
You can use let under ES6:
for(let i = 1; i <= 5; i++) { setTimeout(function() { console.log(i); }, i * 1000); }
You can also use bind to instantly improve your performance:
for(var i = 1; i <= 5; i++) { setTimeout(console.log.bind(console, i), i * 1000); }
Recommended tutorial: "js basic tutorial 》
The above is the detailed content of Discuss the bind() function in javascript. 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

AI Hentai Generator
Generate AI Hentai for free.

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
