search
HomeWeb Front-endJS TutorialDiscuss the bind() function in javascript

Discuss the bind() function in javascript

Jun 15, 2020 pm 04:25 PM
bindjavascript

Discuss the bind() function in javascriptUnderstand 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!

Statement
This article is reproduced at:webhek. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

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 Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools