I've read about the difference between arrow function and regular function in Javascript so I've made a little node.js demo project to understand what I've learned.
let name = 'file Scope'
class User {
name = "Class Scope"
arrow = () => {
console.log("Arrow name " + this.name);
}
normal() {
console.log("Normal name " + this.name);
}
test() {
return {
name: "Object Scope",
n: this.normal,
a: this.arrow,
nested: {
name: 'Nested Object Scope',
nestedNormal: function () {
console.log("Nested Normal " + this.name);
},
nestedArrow: () => {
console.log("Nested Arrow " + this.name);
}
}
}
}
}
let user = new User();
user.test().n(); //Normal name Object Scope
user.test().a();//Arrow name Class Scope
user.test().nested.nestedNormal();//Nested Normal Nested Object Scope
user.test().nested.nestedArrow();//Nested Arrow Class Scope
The console output wasn't expected, I thought the nestedArrow() function would return Object Scope but it returned Class Scope otherwise.
Why did "this.name" refer to the name in class and not to the name inside of the nested object?