<!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
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.