call、apply、bind 是函數控制 this 綁定的三大利器。本文深度解析三者語法差異、參數處理、返回值、核心用例(借用方法、偽數組轉數組、柯里化、事件處理器綁定)、性能基準、常見陷阱與現代替代方案。
| 方法 | 語法 | 參數形式 | 執行時機 | 返回值 |
|---|---|---|---|---|
call | fn.call(thisArg, arg1, arg2, ...) | 展開列表 | **立即執行** | 函數返回值 |
apply | fn.apply(thisArg, [arg1, arg2, ...]) | 數組/類數組 | **立即執行** | 函數返回值 |
bind | fn.bind(thisArg, arg1, arg2, ...) | 展開列表(支援預設參數) | **返回新函數**,稍後調用 | 新函數(this 永久綁定) |
function foo() {
// arguments 是類數組,無 map/filter
const args = Array.prototype.slice.call(arguments); // ES5
const args = Array.from(arguments); // ES6 推薦
const args = [...arguments]; // ES6 展開運算符
}
// DOM 節點列表
const nodes = document.querySelectorAll('div');
Array.prototype.forEach.call(nodes, n => n.classList.add('active'));
// 或
[...nodes].forEach(n => n.classList.add('active'));
function multiply(a, b, c) { return a * b * c; }
const double = multiply.bind(null, 2); // 固定第一參數
double(3, 4); // 24
const triple = multiply.bind(null, 3);
triple(2, 2); // 12
class Component {
constructor() { this.count = 0; }
handleClick() { console.log(this.count++); }
}
const comp = new Component();
// ❌ 錯誤:btn.addEventListener('click', comp.handleClick); // this 指向 btn
// ✅ 正確:
btn.addEventListener('click', comp.handleClick.bind(comp));
// 或類別屬性箭頭函數
handleClick = () => { console.log(this.count++); }
function Parent(name) { this.name = name; }
function Child(name, age) {
Parent.call(this, name); // 借用建構器初始化實例屬性
this.age = age;
}
call / apply:現代引擎高度優化,參數少時 call 略快,參數多/已有數組時 apply 更快。bind:創建新函數有開銷,**熱路徑避免重複 bind**,在構造器/初始化時 bind 一次緩存。this。bind 返回的函數 **無法再次綁定 this**;new boundFn() 時 thisArg 被忽略,但原型鏈保留。call(null, ...) this 為 null;非嚴格模式自動指向全域物件。apply 參數數組過大(>65535)會拋錯,改用展開運算符 fn.call(this, ...args) 或分批。// 替代 bind
const handler = (e) => this.handleClick(e);
// 替代 apply 借用方法
const max = Math.max(...numbers); // 展開運算符
const arr = [...arrayLike]; // 類數組轉數組