JavaScript 函式是一等物件,擁有四種調用模式,每種模式下 this 綁定規則不同。理解這機制是掌握 JS 物件導向與函數式程式設計的關鍵。
| 模式 | 語法 | this 綁定 | 典型場景 |
|---|---|---|---|
| 方法調用 | obj.method() | 調用物件 obj | 物件導向、原型鏈 |
| 函式調用 | func() | 全域物件(非嚴格)/ undefined(嚴格) | 工具函式、回調 |
| 建構子調用 | new Func() | 新建立的實例物件 | 類別實例化、原型繼承 |
| Apply/Call/Bind | func.call(ctx, ...) | 指定的 ctx 物件 | 借用方法、柯里化、綁定回調 |
const myObject = {
name: 'myObject',
value: 0,
increment(num) {
this.value += typeof num === 'number' ? num : 0;
return this; // 鏈式調用
},
toString() {
return `[Object: ${this.name} {value: ${this.value}}]`;
}
};
console.log(myObject.increment(10).increment(20).toString());
// [Object: myObject {value: 30}]
const myObject = {
value: 0,
getInfo() {
// 內部函式 this 指向全域/undefined
const inner = function() {
console.log(this); // window 或 undefined
return this.value; // 無法存取外層 this.value
};
return inner();
}
};
// 解法一:儲存 this 參考(傳統)
getInfoFixed() {
const self = this;
const inner = function() {
return self.value; // 透過 closure 存取
};
return inner();
}
// 解法二:箭頭函式(ES6+ 推薦)
getInfoArrow() {
const inner = () => this.value; // 箭頭函式沒有自己的 this,繼承外層
return inner();
}
// 解法三:bind 綁定
getInfoBind() {
const inner = function() { return this.value; }.bind(this);
return inner();
}
function MyObject(name) {
this.name = name || 'MyObject';
this.value = 0;
this.increment = function(num) {
this.value += typeof num === 'number' ? num : 0;
};
this.toString = function() {
return `[Object: ${this.name} {value: ${this.value}}]`;
};
}
// 原型方法共享
MyObject.prototype.getInfo = function() {
return this.toString();
};
const obj1 = new MyObject('Obj1');
obj1.increment(10);
console.log(obj1.value); // 10
const obj2 = new MyObject('Obj2');
obj2.increment(20);
console.log(obj2.value); // 20
console.log(obj1.getInfo()); // [Object: Obj1 {value: 10}]
function MyObject(name) {
this.name = name || 'MyObject';
this.value = 0;
}
function getInfo() {
return `[Object: ${this.name} {value: ${this.value}}]`;
}
const obj = new MyObject('TestObj');
obj.value = 42;
// call: 參數逐個傳遞
console.log(getInfo.call(obj)); // [Object: TestObj {value: 42}]
// apply: 參數陣列傳遞
function sum(a, b, c) { return a + b + c; }
console.log(sum.apply(null, [1, 2, 3])); // 6
// bind: 回傳綁定 this 的新函式
const boundGetInfo = getInfo.bind(obj);
console.log(boundGetInfo()); // [Object: TestObj {value: 42}]
// 實務:事件處理器綁定
class Component {
constructor() {
this.count = 0;
// 錯誤:this 指向觸發元素
// button.addEventListener('click', this.handleClick);
// 正確:bind 綁定實例
button.addEventListener('click', this.handleClick.bind(this));
// 或箭頭函式屬性
// this.handleClick = () => { ... }
}
handleClick() { this.count++; }
}
function func(a, b) {
console.log('a:', a); // 1
console.log('b:', b); // 2
console.log('arguments:', arguments); // [1, 2, 3, 4, 5] 類陣列
console.log('arguments.length:', arguments.length); // 5
// arguments 不是陣列,但可迭代
for (const arg of arguments) console.log(arg);
// 轉真正陣列
const argsArray = [...arguments];
const argsArray2 = Array.from(arguments);
// 遞迴呼叫自身(arguments.callee 在嚴格模式禁用)
// 現代寫法:具名函式表達式
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
}
func(1, 2, 3, 4, 5);
function foo(a, b, c = 10) {}
console.log(foo.length); // 2(只計算預設值前的參數)
// arguments.length 是實際傳入參數數
function bar(a, b) {}
bar(1, 2, 3); // arguments.length = 3, bar.length = 2
new Fn() → this = 新實例call/apply/bind → this = 指定物件obj.fn() → this = objfn() → this = globalThis (非嚴格) / undefined (嚴格)bindfn.bind(this) 或箭頭函式包裝this,改用參數傳遞eslint 規則 no-invalid-this、prefer-arrow-callback 輔助檢查