-3

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?

  • 1
    `this` is bound to what it was at the time the function was declared. You declare it in the method `test()` of the `user` instance. It takes *that* `this`. – deceze Jan 08 '20 at 14:32
  • 1
    [Useful read](https://stackoverflow.com/questions/59412087/deeply-self-reference-an-objects-properties) - generally `this` when used in an object initialiser will *not* refer to the object that is currently being initialised but the context where the object is being initialised. – VLAZ Jan 08 '20 at 14:33
  • 1
    Also, you seem to be confusing "scope" and "context". Scope is how variables are being looked up, while *context* is the value of `this`. The two are not related to each other. – VLAZ Jan 08 '20 at 14:35

1 Answers1

1

The arrow function is declared inside the test() function so it gets the value of this from that function.

You called user.test() so inside test the value of this is the same as the value of user.

user.name is "Class Scope".

Further reading: Self-references in object literals / initializers.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335