前言
bind() 可以接受多個參數:第一個決定新函數的 this 指向,之後的參數會被當成新函數的預設(前面)參數,再疊上呼叫時實際傳入的參數。
this.x = 9;
var module = {
x: 81,
getX: function () { return this.x; }
};
module.getX(); // 81
var retrieveX = module.getX;
retrieveX(); // 9,此時 this 指向全域物件
// 把 this 綁定到 module,之後不管在哪裡呼叫都指向 module
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81把函數從物件上摘下來單獨呼叫時,this 就會變成全域物件(嚴格模式下是 undefined)。bind() 就是拿來固定這件事的。
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
// 建立一個帶預設參數的新函數
var leadingThirtysevenList = list.bind(undefined, [69, 37], { a: 2 });
var list2 = leadingThirtysevenList(); // [[69,37], {a:2}]
var list3 = leadingThirtysevenList(1, 2, 3); // [[69,37], {a:2}, 1, 2, 3]因為不需要改 this,第一個參數傳 undefined 即可;從第二個參數開始都是要預先塞進去的值。list3 的結果說明了「預設參數在前、呼叫參數在後」的順序。
過去我會這樣寫:
function Coder(name) {
var that = this; // 快取 this
that.name = name;
that.getName = function () { console.log(that.name); };
that.delayGetName = function () {
setTimeout(that.getName, 1000);
};
}
var me = new Coder('Jins');
me.delayGetName(); // 一秒後輸出 Jins多宣告一個 that 總讓人不太舒服。用 bind() 就乾淨多了:
function Coder(name) {
this.name = name;
this.getName = function () { console.log(this.name); };
this.delayGetName = function () {
setTimeout(this.getName.bind(this), 1000);
};
}
var me = new Coder('Jins');
me.delayGetName(); // 一秒後輸出 Jins三者都能改 this,但特性不同:call(thisArg, a, b) 立即執行、參數逐一傳;apply(thisArg, [a, b]) 立即執行、參數用陣列傳;bind() 則是回傳一個新函數,不立即執行,適合用來當回呼或事件處理器。
以上就是本文全部內容,若有疑問歡迎留言交流。