๐ฐarrow function as argument
compared with "normal" functions as parameters
let groupA = {
title: "Group A",
students: ["John", "Pete", "Alice"],
showList() {
// .forEach() โญโโ โญ๏ธ arrow function as argument โโโฎ
this.students.forEach(student =>
console.log(this.title + ': ' + student)
// โฐโโโฏ <---- `this` is taken from the outside โญ๏ธ
);
}
};let groupB = {
title: "Group B",
students: ["Tom", "Bettie", "Joe"],
showList() {
// .forEach() โญโโ โญ๏ธ "normal" function as argument โโโฎ
this.students.forEach(function(student) {
// โฑ โ TypeError or `undefined`
// โญโโ โญ๏ธ โโโฎ
console.log(this.title + ': ' + student);
// โฐโโโฏ <---- โญ๏ธ "normal" function has its own `this`.
// (which is undefined/window/"global object" by default)
// โญ๏ธ possible errors:
// ----------------------------------------------------------------------------
// `this` `this.title` error
// ----------------------------------------------------------------------------
// undefined โ โ TypeError: Cannot read property 'title' of undefined
// window undefined no error
// globalObject undefined no error
// ----------------------------------------------------------------------------
});
}
};Last updated