先看一道面試常見題:
var altwrite = document.write;
altwrite("hello");
// 1. 這段程式碼有什麼問題?
// 2. 正確寫法為何?
// 3. bind() 該怎麼實作?
問題出在 this 的指向。把方法從物件上摘下來單獨呼叫後,this 變成了全域物件,document.write 因此丟失原本的接收者,執行時丟出非法呼叫(Illegal invocation)。正確寫法是用 bind 把 this 綁回 document:
altwrite.bind(document)("hello");
// 或者用 call
altwrite.call(document, "hello");
本文重點在第三題:bind 的各種用法,以及如何自己實作一個。
this.num = 9;
var mymodule = {
num: 81,
getNum: function () { return this.num; }
};
mymodule.getNum(); // 81
var getNum = mymodule.getNum;
getNum(); // 9 —— this 指向了全域物件
var boundGetNum = getNum.bind(mymodule);
boundGetNum(); // 81
把部分參數預先綁定,回傳一個只接受剩餘參數的新函式。
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
var leadingThirtysevenList = list.bind(undefined, 37);
var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
計時器中的 this 預設指向 window。若要在類別方法裡存取實例狀態,就得先綁定。
function Bloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1;
}
Bloomer.prototype.bloom = function () {
window.setTimeout(this.declare.bind(this), 1000);
};
Bloomer.prototype.declare = function () {
console.log('我有 ' + this.petalCount + ' 朵花瓣!');
};
事件處理函式與 setInterval 也適用同樣手法。(箭頭函式同樣能解決這個問題,且更簡潔。)
綁定後的函式仍可用 new 呼叫。此時 this 綁定會被忽略,但預先綁定的參數依然生效。
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return this.x + ',' + this.y;
};
var p = new Point(1, 2);
p.toString(); // '1,2'
var emptyObj = {};
var YAxisPoint = Point.bind(emptyObj, 0 /* x */);
var axisPoint = new YAxisPoint(5);
axisPoint.toString(); // '0,5'
axisPoint instanceof Point; // true
axisPoint instanceof YAxisPoint; // true
因為 Point 與 YAxisPoint 共用同一條原型鏈,所以兩個 instanceof 都成立。
var slice = Array.prototype.slice; slice.call(arguments); // 用 bind 簡化 var unboundSlice = Array.prototype.slice; var slice2 = Function.prototype.call.bind(unboundSlice); slice2(arguments);
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 與原型鏈
這一版引入中轉建構函式 F,讓綁定後的函式與原函式處在同一條原型鏈上,因此用 new 呼叫時 instanceof 仍能正確運作,且此時應把 this 指向新建立的實例而非 context。
Function.prototype.bind = function (context) {
var args = Array.prototype.slice.call(arguments, 1),
F = function () {},
self = this,
bound = function () {
var innerArgs = Array.prototype.slice.call(arguments);
return self.apply(this instanceof F ? this : context,
args.concat(innerArgs));
};
F.prototype = self.prototype;
bound.prototype = new F();
return bound;
};
接近規格的相容版本
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
throw new TypeError("Function.prototype.bind - 目標不是可呼叫物件");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
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;
};
三個重點:typeof 檢查目標是否可呼叫;用 fNOP 保住原型鏈;this instanceof fNOP 判斷是被 new 呼叫還是普通呼叫,據此決定 this 的指向。這也是 MDN 與各個 polyfill 採用的通用寫法。