當將物件的方法直接傳給 forEach 當作回呼時,this 會指向 window(非嚴格模式)或 undefined(嚴格模式),導致無法存取物件屬性:
var json = {
jArray: [],
jPush: function (c) { this.jArray.push(c); }
};
var examp = ['123', '~', '456'];
examp.forEach(json.jPush); // 錯誤:this 指向 window
examp.forEach(json.jPush, json); // 正確,this 綁定到 json
alert(json.jArray); // ['123','~','456']
examp.forEach(function (c) { json.jPush(c); });
examp.forEach(json.jPush.bind(json));
bind 會回傳一個「已綁定 this」的新函式,原函式不受影響,適合函式被多處共用的情境。
examp.forEach(c => json.jPush(c));
箭頭函式沒有自己的 this,會沿用定義時的上下文,也是常見做法。
| 方法 | 適用場景 | 備註 |
|---|---|---|
| forEach(callback, thisArg) | 簡單回呼、不需建立新函式 | 僅限陣列方法 |
| 匿名函式包裹 | 需額外邏輯或多參數 | 較冗長 |
| fn.bind(context) | 函式被多處共用、需保持原函式純粹 | 回傳新函式,效能略低 |
| 箭頭函式 | 現代環境、程式碼簡潔 | 無法再 bind,不適合需動態 this 的情境 |