


Introduction to the role of bind function in javascript_javascript skills
May 16, 2016 pm 04:34 PM<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> button {background-color:#0f0;} </style> </head> <body> <button id="button"> 按钮 </button> <input type="text"> <script> var button = document.getElementById("button"); button.onclick = function() { alert(this.id); // 弹出button }; //可以看出上下文的this 为button </script> </body> </html>
Join bind now
var text = document.getElementById("text");
var button = document.getElementById("button");
button.onclick = function() {
alert(this.id); // popup button
}.bind(text);
//You can see that this in the context is button
At this point you will find that this changes to text
This also applies to function literals, the purpose is to keep the up and down pointing (this) unchanged.
var obj = { color: "#ccc", element: document.getElementById('text'), events: function() { document.getElementById("button").addEventListener("click", function(e) { console.log(this); this.element.style.color = this.color; }.bind(this)) return this; }, init: function() { this.events(); } }; obj.init();
When you click the button, the text in the text will change color. It can be seen that this is not button but obj.
The bind() method is not applicable in IE, 6, 7, and 8. This method needs to be extended by extending the Function prototype.
if (!Function.prototype.bind) { Function.prototype.bind = function(obj) { var slice = [].slice, args = slice.call(arguments, 1), self = this, nop = function() { }, bound = function() { return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments))); }; nop.prototype = self.prototype; bound.prototype = new nop(); return bound; }; }
At this time, you can see that bind() is also supported in ie6, 7, and 8.
slice = Array.prototype.slice,
or
array = Array.prototype.slice.call( array, 0 );
Convert array-like to array

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

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 implement an online speech recognition system using WebSocket and JavaScript

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems

How to implement an online reservation system using WebSocket and JavaScript

How to use JavaScript and WebSocket to implement a real-time online ordering system

Simple JavaScript Tutorial: How to Get HTTP Status Code

JavaScript and WebSocket: Building an efficient real-time weather forecasting system

How to use insertBefore in javascript

How to get HTTP status code in JavaScript the easy way
