萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 使用 bind、forEach 第二參數與箭頭函式正確綁定 this

問題情境

當將物件的方法直接傳給 forEach 當作回呼時,this 會指向 window(非嚴格模式)或 undefined(嚴格模式),導致無法存取物件屬性:

var json = {
    jArray: [],
    jPush: function (c) { this.jArray.push(c); }
};
var examp = ['123', '~', '456'];
examp.forEach(json.jPush); // 錯誤:this 指向 window

解決方案一:forEach 第二參數指定 thisArg

examp.forEach(json.jPush, json); // 正確,this 綁定到 json
alert(json.jArray); // ['123','~','456']

解決方案二:使用匿名函式包裹

examp.forEach(function (c) { json.jPush(c); });

解決方案三:使用 bind 建立綁定後的新函式

examp.forEach(json.jPush.bind(json));

bind 會回傳一個「已綁定 this」的新函式,原函式不受影響,適合函式被多處共用的情境。

補充:ES6 箭頭函式自動捕獲外層 this

examp.forEach(c => json.jPush(c));

箭頭函式沒有自己的 this,會沿用定義時的上下文,也是常見做法。

總結

方法適用場景備註
forEach(callback, thisArg)簡單回呼、不需建立新函式僅限陣列方法
匿名函式包裹需額外邏輯或多參數較冗長
fn.bind(context)函式被多處共用、需保持原函式純粹回傳新函式,效能略低
箭頭函式現代環境、程式碼簡潔無法再 bind,不適合需動態 this 的情境
copyright © 萬盛學電腦網 all rights reserved