call 與 apply 是 Function 原型上的核心方法,作用相同——指定 this 上下文調用函數,唯一區別在參數傳遞方式。
func.call(thisArg, arg1, arg2, ...); // 參數列表
func.apply(thisArg, [argsArray]); // 參數數組(或類數組)
function Rectangle(len, width) {
this.len = len;
this.width = width;
}
function multiply(a, b) {
return a * b;
}
const rect = new Rectangle(15, 30);
// call: 參數逐個傳遞
const area1 = multiply.call(rect, rect.len, rect.width);
// apply: 參數打包為數組
const area2 = multiply.apply(rect, [rect.len, rect.width]);
console.log(area1, area2); // 450 450
// 父構造函數
function Person(name) {
this.name = name;
this.sayHello = function() { return `hello, ${this.name}`; };
}
// 子構造函數
function Student(name, sex, school) {
// 關鍵:借用父構造函數初始化 this
Person.call(this, name);
// 子類自身屬性
this.sex = sex;
this.school = school;
}
const stu = new Student('fengjx', '男', '廣西機電職業技術學院');
console.log(stu.sayHello()); // "hello, fengjx"
console.log(stu.sex, stu.school); // 男 廣西機電職業技術學院
原理:Person.call(this, name) 在子構造函數執行上下文中執行父構造函數,將 this.name、this.sayHello 掛載到子實例上。
// arguments 轉真數組
const args = Array.prototype.slice.call(arguments);
// 或 ES6
const args = [...arguments];
// 遍歷 NodeList
Array.prototype.forEach.call(document.querySelectorAll('div'), el => {
el.style.color = 'red';
});
// Math.max 求數組最大值
Math.max.apply(null, [1, 5, 3]); // 5
// ES6 展開運算符更簡潔
Math.max(...[1, 5, 3]);
| 方法 | 執行時機 | 返回值 | 典型用途 |
|---|---|---|---|
| call | 立即執行 | 函數執行結果 | 動態上下文調用、繼承 |
| apply | 立即執行 | 函數執行結果 | 數組參數、數學運算 |
| bind | 返回新函數 | 綁定後的函數 | 事件處理、柯里化、延遲綁定 |
this 或預綁定 bind。call 分散參數,apply 聚合數組,本質都是顯式綁定 this。掌握它們是理解 JS 函數調用機制、實現繼承、借用原生方法的關鍵。ES6+ 箭頭函數、展開運算符、Reflect.apply 提供了更現代的替代選擇,但理解底層原理仍不可或缺。