Search code examples
javascriptnew-operatorarrow-functionsobject-literal

Javascript arrow function lexical scope: object literal vs "new" operator


I'm trying to understand how arrow functions work in JS. One thing that confuses me is:

let obj1 = { // MDN states that object literal does not create a new scope but I didn't find 
             // any detailed explanation why
  name: "benny",
  getName: () => {
    console.log(this.name);
  },
};
obj1.getName(); // prints "undefined"

class myObj {
  constructor() {
    this.name = "benny";
    this.getName = () => {
      console.log(this.name);
    };
  }
}
let obj2 = new myObj();
obj2.getName(); //prints "benny"

Can somebody please explain why object literal does not create a new scope, while calling "new" does? (I always thought object literal and "new" operator are equal; I didn't find proper explanation in MDN.) I found this explanation on how new operator works. But it's not clear to me why object literal works differently.

Thanks in advance!


Solution

  • The new operator doesn't create a new scope.

    Functions create a new scope.

    The constructor function is a different function to the global-outside-of-any-function space.