深入理解 JavaScript 的 Function.prototype.bind
在 JavaScript 的世界中,this 關鍵字向來是初學者最容易感到困惑、也最容易踩坑的機制之一。
與多數物件導向語言(如 Java 或 C++)不同,JavaScript 中的 this 不是在函式「定義」時決定的,而是在函式「被呼叫(Call-site)」的那一瞬間動態決定的。這種靈活性賦予了 JS 強大的表達力,但也常常導致 this 在非同步回呼(Callback)或事件處理中「走丟」。
為了解決這個核心痛點,ECMAScript 5(ES5)正式引入了 Function.prototype.bind。
一、經典場景:為什麼 this 會走丟?
讓我們先來看一段最典型的物件方法呼叫程式碼:
const starck = {
name: 'Starck',
greet() {
console.log(`Hello, I am ${this.name}`);
},
callBySelf() {
this.greet(); // 這裡由 starck 物件直接呼叫
},
callByWindow() {
// 當作為非同步回呼傳遞時:
setTimeout(this.greet, 100);
}
};
starck.callBySelf(); // 輸出: "Hello, I am Starck"
starck.callByWindow(); // 輸出: "Hello, I am undefined"(在嚴格模式下甚至直接拋出 TypeError)
為什麼 callByWindow 會失敗?
因為當我們把 this.greet 作為參數傳給 setTimeout 時,傳遞的只是函式本身的手柄(Reference)。
當計時器觸發執行時,greet 函式實際上是在全域環境(瀏覽器的 window 物件,或 Node.js 的全域環境)中被單獨調用,此時函式內部的 this 不再指向 starck,而是指向了全域物件。因為 window.name 是空的,所以輸出了 undefined。
二、什麼是 Function.prototype.bind?
bind() 的主要任務,就是將一個函式與指定的物件永久「繫結」在一起。
const boundFunction = fn.bind(thisArg[, arg1[, arg2[, ...]]]);
核心特性
- 不會立刻執行:不同於
call()或apply()會在傳入時立刻觸發執行,bind()會回傳一個全新包裝後的函式(Bound Function)。 - 永久鎖定
this:新回傳的函式,無論未來被轉交給誰、在何處、以何種方式調用,其內部的this都會被牢牢鎖定為你當初傳入的thisArg。
修復上面的非同步回呼問題:
const starck = {
name: 'Starck',
greet() {
console.log(`Hello, I am ${this.name}`);
},
callCorrectly() {
// 使用 bind 鎖定 this 為目前的 starck 物件
setTimeout(this.greet.bind(this), 100);
}
};
starck.callCorrectly(); // 輸出: "Hello, I am Starck"(100ms 後正常印出)
三、三兄弟對決:bind、call 與 apply
這三個掛載在 Function.prototype 上的方法都能手動指定 this,但使用時機各有不同:
| 方法 | 執行時機 | 參數傳遞方式 | 回傳值 | 典型使用場景 |
|---|---|---|---|---|
call() |
立即執行 | 逐一列出:fn.call(thisObj, a, b, c) |
原函式的執行結果 | 借用其他物件的方法 |
apply() |
立即執行 | 陣列形式:fn.apply(thisObj, [a, b, c]) |
原函式的執行結果 | 參數已整理為陣列時(如 Math.max.apply(null, arr)) |
bind() |
延遲執行 | 逐一列出:fn.bind(thisObj, a, b) |
回傳一個全新的繫結函式 | 事件監聽器、非同步回呼、偏函數套用 |
function introduce(greeting, punctuation) {
console.log(`${greeting}, I'm ${this.name}${punctuation}`);
}
const user = { name: 'Alice' };
// 1. call: 立即執行
introduce.call(user, 'Hi', '!'); // "Hi, I'm Alice!"
// 2. apply: 立即執行,參數用陣列包裹
introduce.apply(user, ['Hey', '...']); // "Hey, I'm Alice..."
// 3. bind: 不執行,回傳新函式
const boundIntro = introduce.bind(user);
boundIntro('Hello', '.'); // "Hello, I'm Alice."
四、進階威力:偏函數與柯里化(Partial Application)
bind() 的另一個強大之處在於:除了綁定 this 之外,你還可以預先填入一部分的初始參數(Leading Arguments)。
這種在函數式編程(Functional Programming)中被稱為偏函數(Partial Application):
function multiply(factor, number) {
return factor * number;
}
// 建立一個專門「翻倍(乘 2)」的專用函式
// 這裡 this 不需要特別指定,傳入 null 即可
const double = multiply.bind(null, 2);
console.log(double(4)); // 輸出: 8
console.log(double(10)); // 輸出: 20
// 建立一個「乘 5」的函式
const quintuple = multiply.bind(null, 5);
console.log(quintuple(3)); // 輸出: 15
新函式在被調用時,會自動將後續傳入的參數拼接在預設參數之後。
五、現代 JavaScript 的演進:箭頭函式(Arrow Functions)
在 ES6(ECMAScript 2015)普及後,JavaScript 引入了箭頭函式(=>)。
箭頭函式最大的特色就是沒有自己的 this,它的 this 永遠繼承自外層範疇(Lexical this):
// 現代語法:直接使用箭頭函式捕獲外層 this
const starckModern = {
name: 'Starck',
callByArrow() {
setTimeout(() => {
console.log(`Hello, I am ${this.name}`);
}, 100);
}
};
starckModern.callByArrow(); // "Hello, I am Starck"
那 bind() 已經過時了嗎?
並沒有。雖然在日常事件回呼中箭頭函式更為輕巧直覺,但在以下場景中 bind() 依然無可取代:
- 方法分離與借用:例如將原生方法抽離為獨立函式(如
const hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);)。 - 函數式編程中的偏函數(Partial Application):動態預設高階函式的參數。
- 老舊框架與 Class 元件:在早期的 React Class Component 中,在建構子執行
this.handleClick = this.handleClick.bind(this)是標準效能優化寫法。
結語
Function.prototype.bind 不僅僅是一個防範 this 遺失的防禦工具,更是深入理解 JavaScript 執行環境(Execution Context)、閉包(Closure)與原型鏈(Prototype Chain)的重要基石。搞懂它,你在閱讀與撰寫複雜的 JavaScript 程式庫時便能游刃有餘。