๐ฐarrow function as argument
compared with "normal" functions as parameters
JS โฉ objects โฉ arrow function โฉ as argument
in the body of an arrow function๏ผthis is taken from the outside context.
๐พ replit๏ผarrow function as argument
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 โญ๏ธ
);
}
};
"normal" function as argument๏ผ
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: Alice
groupB.showList(); // this = globalObject (in Node's environment โญ๏ธ)
// undefined: Tom
// undefined: Bettie
// undefined: Joe
Last updated
Was this helpful?