🔰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: JoeLast updated
Was this helpful?