<!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>此時加入bind
複製代碼代碼如下:
var text = document.getElementById("text");
var button = document.getElementById("button");
button.onclick = function() {
alert(this.id); // 彈出button
}.bind(text);
//可以看出上下文的this 為button
此時會發現this改變為text
函數字面量裡也適用,目的是保持上下指向(this)不變。
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();此時點擊按鈕text裡的字會變色。可見this不為button而是obj。
bind()的方法在ie,6,7,8中不適用,需要擴展通過擴展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;};}此時可以看到ie6,7,8中也支持bind()。
複製代碼代碼如下:
slice = Array.prototype.slice,
或
array = Array.prototype.slice.call( array, 0 );
將類似數組轉換為數組