bind() 與 call()/apply() 一樣能改變 this 指向,但 **不立即執行**,而是返回一個 **新函數**(綁定後的函數),調用新函數時 this 永久綁定為指定對象。
var obj = { a: 1, b: 2, getCount(c, d) { return this.a + this.b + c + d; } };
window.a = window.b = 0;
console.log(obj.getCount(3, 4)); // 10 (this=obj)
var func = obj.getCount;
console.log(func(3, 4)); // 7 (this=window, a=b=0)
// bind 綁定 this
var bound = obj.getCount.bind(obj);
console.log(bound(3, 4)); // 10 (this 永久綁定為 obj)
func.bind(thisArg, arg1, arg2, ...)
thisArg:新函數運行時的 this 值。arg1, arg2...:預設參數,調用新函數時會插入到實參前面(偏函數應用)。function add(a, b, c) { return a + b + c; }
var add10 = add.bind(null, 10); // 固定第一參數為 10
console.log(add10(2, 3)); // 15 (10+2+3)
console.log(add10(5, 5)); // 20 (10+5+5)
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)));
};
};
}
核心:閉包保存 self(原函數)和 args(預設參數),返回新函數內部用 apply 執行。
| 特性 | bind | call / apply |
|---|---|---|
| 執行時機 | 返回新函數,**延後執行** | **立即執行** |
| 返回值 | 新函數 | 原函數執行結果 |
| 參數傳遞 | 預設參數 + 調用時參數 | 僅調用時參數 |
| this 綁定 | 永久綁定 | 單次調用綁定 |
class Handler {
constructor() { this.count = 0; }
click() { console.log(++this.count); }
}
const h = new Handler();
btn.addEventListener('click', h.click.bind(h)); // this 永遠指向 h
setTimeout(obj.method.bind(obj), 1000);
[1,2,3].map(func.bind(context));
const log = console.log.bind(console, '[DEBUG]');
log('message'); // [DEBUG] message
const slice = Array.prototype.slice.bind(arguments); // 類數組轉數組
箭頭函數無自身 this,捕獲外層 this,**無法被 bind 改變**;
const arrow = () => this;
arrow.bind({a:1})(); // 仍指向外層 this,bind 無效
因此箭頭函數天然適合作為回調,無需 bind。