把物件方法當成回呼函數傳出去,是 JavaScript 新手最常踩的坑之一——方法裡的 this 會悄悄換成 window。
var json = {
jArray: [],
jPush: function (c) {
this.jArray.push(c);
}
}
var examp = ["123", "~", "456"];
examp.forEach(json.jPush); // 報錯
原因很單純:jPush 被當成獨立函數傳給 forEach 後,呼叫時的接收者不再是 json,而是 window,於是 this.jArray 變成 undefined。
forEach 本身接受一個 thisArg,可以指定 this:
examp.forEach(json.jPush, json); alert(json.jArray); // 123~456
examp.forEach(function (c) {
json.jPush(c);
});
alert(json.jArray); // 123~456
examp.forEach(json.jPush.bind(json)); alert(json.jArray);
bind 的重點在於它建立一個新函數,而不是修改原函數。新函數的行為與原函數一致,只是接收者被固定成我們指定的物件,原本的方法則完全不受影響。
這也意味著 bind 用起来相當安全:當一個方法被多處共用時,不必擔心替某一處綁定 this 會污染其他呼叫點。