bind 的主要用途,是建立一個新的函式,並固定其 this 指向。當事件處理或 callback 需要保持特定物件作為 this 時,bind 就非常有用。
var button = document.getElementById("button");
button.onclick = function () {
alert(this.id);
};在這個例子中,this 指向 button。若我們希望 this 改為其他物件,就可以使用 bind。
var text = document.getElementById("text");
var button = document.getElementById("button");
button.onclick = function () {
alert(this.id);
}.bind(text);此時 this 不再指向 button,而是指向 text。
var obj = {
color: "#ccc",
element: document.getElementById("text"),
events: function () {
document.getElementById("button").addEventListener("click", function () {
this.element.style.color = this.color;
}.bind(this));
return this;
},
init: function () {
this.events();
}
};
obj.init();在事件監聽器中,this 預設可能指向觸發事件的元素。透過 bind(this),可以讓事件處理函式保持存取 obj 的能力。
IE6、IE7、IE8 不支援 Function.prototype.bind,可以自行擴充。
if (!Function.prototype.bind) {
Function.prototype.bind = function (obj) {
var slice = [].slice;
var args = slice.call(arguments, 1);
var self = this;
var nop = function () {};
var bound = function () {
var context = this instanceof nop ? this : (obj ? obj : {});
return self.apply(context, args.concat(slice.call(arguments)));
};
nop.prototype = self.prototype;
bound.prototype = new nop();
return bound;
};
}另外,Array.prototype.slice.call 常用來把類陣列物件轉成真正的陣列,例如 function 的 arguments。