ECMAScript 提供眾多的 Higher Order Function,如 Array.prototype.forEach() ,當我們將 Callback 傳入後,且該 Callback 含有 this 想讀取 Object 的 Property 時,就會出現錯誤,該怎避免這個常見的問題呢 ?
Version
macOS Catalina 10.15
VS Code 1.38.1
Quokka 1.0.254
ECMAScript 5
ECMAScript 2015
For Loop
let student = {
name: 'Sam',
friends: ['Kevin', 'John', 'Mike'],
sayHello: function() {
for(var i = 0; i < this.friends.length; i++)
console.log(`${this.name} say Hello to ${this.friends[i]}`);
}
};
student.sayHello();
一個常見的 OOP 需求,object 內有 property,而 method 想要讀取 property 的值。
若使用 for loop 搭配 this 讀取 property,則完全沒有問題。

Array.prototype.forEach()
let student = {
name: 'Sam',
friends: ['Kevin', 'John', 'Mike'],
sayHello: function() {
this.friends.forEach(function(friend) {
console.log(`${this.name} say Hello to ${friend}`);
});
}
};
student.sayHello();
若將 for loop 改成 Array.prototype.forEach() 後,改傳入 callback 進 forEach()。
因為 callback 是獨立 function,所以 this 為 undefined,並不是如 sayHello() 是掛在 student 的 function,所以 this 指向 student。
因為 sayHello() 是 student 的 method,所以 this 指向 student,但傳入 forEach() 的 function 並不是 student 的 method,所以 this 指向 undefined。
這該怎麼解決呢 ?

Self
let student = {
name: 'Sam',
friends: ['Kevin', 'John', 'Mike'],
sayHello: function() {
let self = this;
this.friends.forEach(function(friend) {
console.log(`${self.name} say Hello to ${friend}`);
});
}
};
student.sayHello();
最傳統、最常見的方法就是將 this 指定給 self,如此傳入 forEach() 的 callback 可透過 lexical scope 存取 self。

Bind
let student = {
name: 'Sam',
friends: ['Kevin', 'John', 'Mike'],
sayHello: function() {
this.friends.forEach(function(friend) {
console.log(`${this.name} say Hello to ${friend}`);
}.bind(this));
}
};
student.sayHello();
既然傳入 forEach() 的 function 的 this 不見了,我們可以透過 bind() 再度將 this 綁定進去,它將回傳一個 this 指向 student 的新 function 為 callback。

forEach 傳入 this
let student = {
name: 'Sam',
friends: ['Kevin', 'John', 'Mike'],
sayHello: function() {
this.friends.forEach(function(friend) {
console.log(`${this.name} say Hello to ${friend}`);
}, this);
}
};
student.sayHello();
其實 Array.prototype 下的 method,除了傳入 function 外,還有第二個 argument 可將 this 傳進去,如此可解決 callback 的 this 不見問題。

Arrow Function
let student = {
name: 'Sam',
friends: ['Kevin', 'John', 'Mike'],
sayHello: function() {
this.friends.forEach(friend => console.log(`${this.name} say Hello to ${friend}`));
}
};
student.sayHello();
最漂亮的解法是改用 ECMAScript 2015 的 Arrow Function,它沒有自己的 this,而會使用 parent scope 的 this,也就是 sayHello() 的 this,因此可以順利讀取到 object 的 property。

Conclusion
- 只要在 object 的 method 中 以 callback 傳到其他 higher order function 時,卻又試圖存取 object 的 property,就會踩到這個雷,有多種解法可以解決,但最優雅的就是 ES6 的 arrow function