Home > Article > Web Front-end > 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!