2

Arrow functions have a bound lexical scope. So in this code person.person1.sayName() is supposed to output HB but instead it outputs GOT (the global scope). Why is this so?

var name = "GOT";
var person = {
   name : "HB",
   sayName : function() { return this.name },
   person1 : {
       name : "WW",
       sayName : () => this.name
    }
};
console.log(person.person1.sayName());
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Rajkumar Somasundaram
  • 1,225
  • 2
  • 10
  • 20

1 Answers1

4

Behavior is as expected. Because it's an arrow function, the calling context is inherited from the outer scope (the block in which person is defined, in which this refers to the global object), not from the outer object in which person1 is nested. No calling context is captured when sayName is called, and (possibly nested) object initializers do not create a new scope.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320