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// ---------------------------------------------------------------------------- }); }};
results๏ผ
groupA.showList(); // this = groupA// Group A: John// Group A: Pete// Group A: AlicegroupB.showList(); // this = globalObject (in Node's environment โญ๏ธ)// undefined: Tom// undefined: Bettie// undefined: Joe