function add(a, b) { alert(a + b); }
function sub(a, b) { alert(a - b); }
add.call(sub, 1, 3); // 4 —— 將 add 的邏輯套用到 sub 上下文(此處 sub 只是作為 this,實際執行 add 代碼)
語法:func.call(thisArg, arg1, arg2, ...)
add.apply(sub, [1, 3]); // 4 —— 唯一差別:第二參數為陣列/類陣列
function showThis() { alert(this); }
showThis(); // window
showThis.call(); // window
showThis.call("abc"); // "abc" (字串被包裝為 String 物件)
function Animal(name) {
this.name = name;
this.showName = function() { alert(this.name); };
}
function Cat(name) {
Animal.call(this, name); // 繼承 Animal 實例屬性/方法
}
var cat = new Cat("Black Cat");
cat.showName(); // "Black Cat"
var boundShow = cat.showName.bind(cat);
setTimeout(boundShow, 1000); // 1 秒後正確輸出 "Black Cat"
// 手動實現 bind(兼容舊環境)
if (!Function.prototype.bind) {
Function.prototype.bind = function(context) {
var fn = this, args = Array.prototype.slice.call(arguments, 1);
return function() {
return fn.apply(context, args.concat(Array.prototype.slice.call(arguments)));
};
};
}
class MyClass {
constructor() {
this.el = document.createElement('div');
// 使用 bind 確保 onClick 內的 this 指向 MyClass 實例
this.el.addEventListener('click', this.onClick.bind(this));
}
onClick(e) { console.log(this === myInstance); // true }
}
function demo() {
// arguments 是類陣列,無 slice 方法
var args = Array.prototype.slice.call(arguments); // 轉為真陣列
// ES6 更簡單:const args = [...arguments]; 或 Array.from(arguments);
}
| 方法 | 參數形式 | 回傳值 | 典型用途 |
|---|---|---|---|
| call | 展開列表 | 函數執行結果 | 立即調用、繼承借用、借用方法 |
| apply | 陣列/類陣列 | 函數執行結果 | 參數已在陣列中、Math.max.apply(null, arr) |
| bind | 展開列表 | 新函數(永久綁定 this) | 事件回調、延遲調用、柯里化 |