<!DOCTYPE html><html><head><meta charset="utf-8"><style>button {background-color:#0f0;}</style></head><body><button id="button"> button</button><input type="text"><script>var button = document.getElementById("button");button.onclick = function() {alert(this.id); // pop-up button};// This in the context can be seen as button</script></body></html>Join bind
The code copy is as follows:
var text = document.getElementById("text");
var button = document.getElementById("button");
button.onclick = function() {
alert(this.id); // pop-up button
}.bind(text);
//This in the context can be seen as button
At this time, you will find that this has changed to text
It is also applicable in function literals, with the purpose of keeping the up and down direction (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();At this time, clicking the button text will change color. It can be seen that this is not a button but obj.
The method of bind() is not applicable in ie, 6, 7, 8. It is necessary to extend this method 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.
The code copy is as follows:
slice = Array.prototype.slice,
or
array = Array.prototype.slice.call( array, 0 );
Convert an array like to an array