JavaScript 中函式的 this 由呼叫方式決定。直接引用方法會導致上下文丟失:
var log = console.log;
log('info...'); // TypeError: Illegal invocation
// 因為 log 現在以函式形式呼叫,this 指向 window,非 console
var log = console.log.bind(console);
log('info...'); // 正常運作,this 永遠綁定為 console
bind 回傳新函式,內部透過 apply 強制指定 this,經典閉包應用。
if (!Function.prototype.bind) {
Function.prototype.bind = function(context) {
var fn = this;
return function() {
return fn.apply(context, arguments);
};
};
}
核心:閉包保存 fn(原函式)與 context(目標 this),呼叫時以 apply 套用。
bind(context, arg1, arg2) 可預先綁定參數(偏函式應用)。element.addEventListener('click', handler.bind(this)) 確保處理器內 this 指向元件實例。Array.prototype.slice.bind(arguments) 將類陣列轉真陣列。bind 回傳新函式,**原函式不變**;多次 bind 會疊加包裹,效能微損。bind 無效,勿對箭頭函式使用。bind 後仍可 new,this 指向新實例,但原型鏈保持不變(ES2015 規範)。