Arrow functions revisited
Arrow functions have no “this”
// 箭頭函式沒有 this 會從外部獲取
let group = {
title: "Our Group",
students: ["John", "Pete", "Alice"],
showList() {
this.students.forEach(
student => alert(this.title + ': ' + student)
);
}
};
group.showList();
// forEach 執行函式預設 this = undefined
let group = {
title: "Our Group",
students: ["John", "Pete", "Alice"],
showList() {
this.students.forEach(function(student) {
// Error: Cannot read property 'title' of undefined
alert(this.title + ': ' + student)
});
}
};
group.showList();
// 箭頭函式不能使用建構函式Arrows have no “arguments”
Last updated
Was this helpful?