Function.prototype.call() 允許在指定 this 上下文中調用函數,並接受參數列表。是實現繼承、借用方法、顯式綁定上下文的核心工具。
func.call(thisArg, arg1, arg2, ...)
thisArg:函數執行時的 this 值。非嚴格模式下 null/undefined 指向全局對象 (window),原始值會被包裝為對象。arg1, arg2...:傳遞給函數的參數列表(與 apply 的數組參數不同)。function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
var obj = { name: 'Alice' };
greet.call(obj, 'Hello', '!'); // "Hello, Alice!"
var obj1 = { name: 'A', say: function() { console.log(this.name); } };
var obj2 = { name: 'B' };
obj1.say.call(obj2); // "B" - obj2 借用 obj1.say
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0) throw RangeError('價格不能為負');
}
function Food(name, price) {
Product.call(this, name, price); // 繼承 Product 屬性
this.category = 'food';
}
Food.prototype = Object.create(Product.prototype);
Food.prototype.constructor = Food;
var cheese = new Food('feta', 5);
console.log(cheese.name, cheese.price, cheese.category); // feta 5 food
function toArray(args) {
return Array.prototype.slice.call(arguments);
// 或 ES6: return [...arguments];
}
console.log(toArray(1,2,3)); // [1,2,3]
var handler = {
message: 'Event fired',
handleClick: function() { console.log(this.message); }
};
// 錯誤:btn.onclick = handler.handleClick; // this 指向 btn
// 正確:
btn.onclick = handler.handleClick.bind(handler);
// 或舊式:
btn.onclick = function() { handler.handleClick.call(handler); };
| 方法 | 參數形式 | 返回值 | 執行時機 |
|---|---|---|---|
| call | 列表 | 函數返回值 | 立即執行 |
| apply | 數組/類數組 | 函數返回值 | 立即執行 |
| bind | 列表 | 新函數 (綁定 this) | 稍後調用 |
'use strict';
function f() { return this; }
f.call(null); // null (非嚴格模式下為 window)
f.call(undefined); // undefined
f.call(7); // Number {7} (原始值被包裝)