bind() 核心作用
創建一個新函數,調用時 this 永久綁定到指定對象,並可預設參數 (柯里化)。
基本語法與用法
function.fn.bind(thisArg, arg1, arg2, ...)
// 1. 綁定 this
var obj = {x: 42};
function foo() { console.log(this.x); }
var bound = foo.bind(obj);
bound(); // 42
// 2. 柯里化:預設參數
function add(a, b, c) { return a + b + c; }
var add5 = add.bind(null, 5); // a=5
var add5_10 = add5.bind(null, 10); // a=5, b=10
console.log(add5_10(3)); // 18 (5+10+3)
// 3. 事件處理器綁定
button.addEventListener('click', handler.bind(this));
// 4. 延遲調用保持上下文
setTimeout(obj.method.bind(obj), 1000);
偽實現原理 (ES5 環境)
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
throw new TypeError('Function.prototype.bind - not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1);
var fToBind = this;
var fNOP = function() {};
var fBound = function() {
// 關鍵:this instanceof fNOP 判斷是否作為構造函數調用 (new bound())
return fToBind.apply(
this instanceof fNOP && oThis ? this : oThis,
aArgs.concat(Array.prototype.slice.call(arguments))
);
};
// 維護原型鏈:bound.prototype -> fToBind.prototype
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
關鍵設計細節解析
- 構造函數調用支持:
new BoundFn() 時,this 應指向新實例而非綁定對象。this instanceof fNOP 檢測此情況。
- 原型鏈繼承:
fBound.prototype = new fNOP() 使 bound.prototype.__proto__ === fToBind.prototype,保證 instanceof 正常工作。
- 參數合併:綁定時參數
aArgs + 調用時參數 arguments。
- length 屬性:標準規定
bound.length = Math.max(fToBind.length - aArgs.length, 0),Polyfill 常忽略。
實戰場景對比
| 場景 | 舊寫法 (self/that) | bind() 寫法 |
| 回調函數保持 this | var that=this; cb(function(){that.method();}) | cb(this.method.bind(this)) |
| 事件監聽器移除 | el.addEventListener('click', fn); el.removeEventListener('click', fn); // 需保存 fn 引用 | var bound = fn.bind(this); el.addEventListener('click', bound); el.removeEventListener('click', bound); |
| 柯里化工廠函數 | function makeAdder(a){return function(b){return a+b;}} | add.bind(null, a) |
| 陣列方法傳遞 this | [1,2,3].map(function(x){return this.mul(x);}, this) | [1,2,3].map(this.mul.bind(this)) |
箭頭函數 vs bind()
// 箭頭函數:詞法綁定 this (定義時捕獲外層 this)
var obj = {
value: 42,
getArrow: () => () => this.value, // 錯誤!this 指向 window/module
getBind: function() { return function() { return this.value; }.bind(this); }
};
// 正確箭頭函數用法
var obj2 = {
value: 42,
getValue: function() {
return () => this.value; // 內層箭頭函數捕獲外層函數的 this
}
};
瀏覽器兼容性與 Polyfill 策略
| 環境 | 支援 | 策略 |
| Chrome 7+ / Firefox 4+ / Safari 5.1.4+ / Edge 12+ / IE 9+ | 原生支援 | 直接使用 |
| IE 6-8 | 不支援 | 引入 ES5-Shim 或上方 Polyfill |
| Node.js 所有版本 | 原生支援 | 直接使用 |
現代最佳實踐
- 優先用箭頭函數:類方法定義為箭頭函數
method = () => {} 自動綁定實例,無需 bind。
- React 類組件:構造函數中
this.handleClick = this.handleClick.bind(this) 或 handleClick = () => {}。
- 事件監聽器:綁定後保存引用以便移除,或用
{once: true} 選項。
- 避免濫用 bind:每次調用創建新函數,高頻調用 (如 render、map) 有性能開銷,優先考慮箭頭函數或閉包。