先看一道經典題:
var write = document.write;
write("hello");
// 1. 以上程式碼有什麼問題?
// 2. 正確寫法應該是什麼?
這段程式會拋出「非法呼叫」錯誤。原因是我們把 write 從 document 上摘下來單獨執行,函式因此失去了上下文,this 指向全域物件,瀏覽器自然不允許。
解法是明確指定 this,bind、call、apply 三者都能勝任:
var write = document.write;
write.bind(document)('hello'); // bind:回傳新函式
write.call(document, 'hello'); // call:立即執行,參數逐一傳入
write.apply(document, ['hello']); // apply:立即執行,參數放陣列
bind() 最單純的用法,是建立一個無論怎麼呼叫都保有相同 this 的函式。以下範例很清楚地呈現差異:
<script type="text/javascript">
this.num = 9;
var module = {
num: 81,
getNum: function () { console.log(this.num); }
};
module.getNum(); // 81,this 指向 module
var getNum = module.getNum;
getNum(); // 9,this 指向 window / global
var boundGetNum = getNum.bind(module);
boundGetNum(); // 81,this 被固定為 module
</script>
偏函式指的是:把一個接受多個參數的函式,先綁定其中若干參數,回傳一個只接受剩餘參數的新函式。用 bind 就能優雅做到:
<script type="text/javascript">
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3);
console.log(list1); // [1, 2, 3]
// 預先綁定第一個參數為 37
var leadingThirtysevenList = list.bind(undefined, 37);
console.log(leadingThirtysevenList()); // [37]
console.log(leadingThirtysevenList(1, 2, 3)); // [37, 1, 2, 3]
</script>
計時器中的 this 預設指向全域物件。當我們希望在類別方法裡存取實例狀態時,就用 bind 把 this 綁進回呼:
<script type="text/javascript">
function Bloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1;
}
// 一秒後呼叫 declare
Bloomer.prototype.bloom = function () {
window.setTimeout(this.declare.bind(this), 1000);
};
Bloomer.prototype.declare = function () {
console.log('我有 ' + this.petalCount + ' 朵花瓣!');
};
var test = new Bloomer();
test.bloom();
</script>
綁定後的函式也能用 new 建構實例,此時傳入的 this 會被忽略,但預綁定的參數仍然有效:
<script type="text/javascript">
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
console.log(this.x + ',' + this.y);
};
var p = new Point(1, 2);
p.toString(); // 1,2
var YAxisPoint = Point.bind(null, 10); // 預綁定 x = 10
var axisPoint = new YAxisPoint(5);
axisPoint.toString(); // 10,5
console.log(axisPoint instanceof Point); // true
console.log(axisPoint instanceof YAxisPoint); // true
console.log(new Point(17, 42) instanceof YAxisPoint); // true
</script>
Point 與 YAxisPoint 共用同一條原型鏈,所以 instanceof 判斷皆為真。
bind() 是 ES5 才加入的,舊環境不一定有。最樸素的實作是先保存 this,回傳一個套用原函式的新函式:
Function.prototype.bind = function (context) {
var self = this; // 保存呼叫 bind 的目標函式
return function () {
return self.apply(context, arguments);
};
};
加上柯里化支援,就能在綁定時預先傳入參數:
Function.prototype.bind = function (context) {
var args = Array.prototype.slice.call(arguments, 1), self = this;
return function () {
var innerArgs = Array.prototype.slice.call(arguments);
return self.apply(context, args.concat(innerArgs));
};
};
更嚴謹的版本還要處理原型鏈——讓綁定後的函式與原函式位於同一條原型鏈上,這樣用 new 呼叫時 instanceof 才會正確:
Function.prototype.bind = function (context) {
var args = Array.prototype.slice.call(arguments, 1);
var F = function () {}, self = this;
var bound = function () {
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs);
return self.apply((this instanceof F ? this : context), finalArgs);
};
F.prototype = self.prototype;
bound.prototype = new F();
return bound;
};
這段出自《JavaScript Web Application》,透過中轉建構函式 F 銜接原型,是最完整的實作。若要直接放進瀏覽器當 polyfill,可再補上型別檢查:
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
throw new TypeError("Function.prototype.bind - 嘗試綁定的目標不是可呼叫物件");
}
var aArgs = Array.prototype.slice.call(arguments, 1);
var fToBind = this;
var fNOP = function () {};
var fBound = function () {
return fToBind.apply(
this instanceof fNOP && oThis ? this : oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments))
);
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
第一,bind 解決的是「函式被搬離原物件後失去 this」的問題。第二,它能做偏函式,預先固定部分參數。第三,它的回傳值是一個新函式,這一點與立即執行的 call/apply 有本質差異——需要延後執行或當回呼使用時,就該選 bind。