JavaScript 中階
如何使用 call、apply 或 bind?
概述
call、apply、bind 都是用來手動指定函式的 this,屬於顯式綁定(Explicit Binding)。
call
立即執行函式,第一個參數為 this,後續參數逐一傳入。
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const user = { name: 'Alice' };
greet.call(user, 'Hello', '!'); // 'Hello, Alice!'
apply
立即執行函式,第一個參數為 this,後續參數以陣列傳入。
greet.apply(user, ['Hi', '?']); // 'Hi, Alice?'
// 實用技巧:展開陣列
const nums = [3, 1, 4, 1, 5, 9];
Math.max.apply(null, nums); // 9(等同 Math.max(...nums))
bind
不立即執行,回傳一個新函式,永久將 this 綁定到指定物件。
const greetAlice = greet.bind(user, 'Hey');
greetAlice('!'); // 'Hey, Alice!'
greetAlice('.'); // 'Hey, Alice.'
// 常見用途:React 類別元件的事件處理
class Button extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() { /* this 正確指向元件 */ }
}
比較表
| 方法 | 執行時機 | 參數傳遞 | 回傳值 |
|---|---|---|---|
call |
立即 | 逐一 | 函式執行結果 |
apply |
立即 | 陣列 | 函式執行結果 |
bind |
延遲 | 逐一(可部分) | 新函式 |
記憶口訣
call→ Comma(逗號分隔參數)apply→ Array(陣列參數)bind→ Bind(綁定,不立即執行)
✦ AI 模擬面試
輸入你的答案,AI 即時分析精準度與改進空間
登入後即可使用 AI 評分
