把物件方法當回呼函式傳給事件時,this 會變成觸發事件的那個 DOM 元素,而不是原本的物件,導致 this.title 拿到 undefined。這個問題有個漂亮的解法:幫 Function 擴充一個 bind。
Function.prototype.bind = function (obj) {
var _this = this; // 記下原函式
return function () {
_this.apply(obj, arguments); // 用指定物件作為 this 呼叫
};
};
原理是閉包:bind 回傳一個新函式,該函式在未來被執行時,用 apply 強制把 this 指向我們指定的 obj,同時把參數原封不動轉發過去。
var a = function () {
alert(this.title);
}.bind(document);
a(); // 此時 this 就是 document
function myalert() {
this.title = 'hello world';
this.init = function () {
$("#xxx").click(this.close.bind(this));
};
this.close = function () {
alert(this.title);
};
}
var a = new myalert();
a.init();
如果不加 .bind(this),點擊 #xxx 時瀏覽器會以該元素為 this 呼叫 close,this.title 自然是 undefined。加上之後,this 被鎖定回 myalert 的執行個體,值就取得回來了。
ES5 起 Function.prototype.bind 已是標準方法,現代瀏覽器不必自己實作。因此實務上更建議寫成向下相容的形式:
if (!Function.prototype.bind) {
Function.prototype.bind = function (context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
return function () {
return self.apply(context, args.concat(Array.prototype.slice.call(arguments)));
};
};
}
這個版本比最簡單的寫法多了兩件事:一是先判斷避免覆蓋原生實作,二是支援「部分套用」——bind 時傳入的參數會排在呼叫時參數的前面,這是原生 bind 的規格行為。
兩者都能改寫 this,差別只在參數形式:fn.call(obj, a, b) 逐一列出,fn.apply(obj, [a, b]) 收在陣列裡。若要在未知參數個數時轉發,apply 會方便得多,上面的 bind 擴充正是用了這個特性。