bind 存在的唯一理由,就是「把 this 固定下來」。要理解它,先看一個沒有 bind 的例子。
<!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
};
</script>
</body>
</html>
點下去會跳出 button,因為事件處理函式裡的 this 指向綁定事件的元素本身。
var text = document.getElementById("text");
var button = document.getElementById("button");
button.onclick = function() {
alert(this.id); // 原本會彈出 button
}.bind(text);
// bind 之後 this 被固定為 text
此時點擊按鈕,跳出的是 text 的 id。這正是 bind 的效果:回傳一個新函式,其 this 永遠指向傳入的物件,之後不論怎麼被呼叫都不會改變。
在物件字面量中,事件回呼經常會讓 this 跑掉,bind 就是為了守住這條指向:
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 裡的文字會變色。若沒有 .bind(this),回呼裡的 this 會是 button,this.color 也就變成 undefined。值得一提的是,箭頭函式同樣能解決這個問題,而且在現代程式碼中更常見。
IE6~8 沒有原生 bind,可以掛到 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;
};
}
這段 polyfill 同時處理了「預綁參數」與「用 new 呼叫時 this 的判定」,是相當經典的實作。
上面用到的 slice 借用技巧值得記住:
slice = Array.prototype.slice; // 或 array = Array.prototype.slice.call(array, 0);
arguments、NodeList 這類「長得像陣列但不是陣列」的物件,都能靠這招轉成真正的陣列,之後就能使用 forEach、map 等方法。