0

I know arrow functions don't have its own 'this' and references its parents and thus I assumed it to be pointing to its parent's 'this' i.e. obj. Would really appreciate if someone could answer this.

var obj = {
   fullname: 'Jack',
   prop: {
      fullname: 'John',
      getFullname: () => {
         return this.fullname;
      }
   }
};

console.log(obj.prop.getFullname()); // undefined, as this is window not obj or prop
var test = obj.prop.getFullname;
console.log(test()); // undefined
  • Because arrow functions *close over* `this`, and apparently your code is running at global scope (not inside a module of function). `this` at global scope is `window` on browsers (speaking slightly loosely). See [this question's answers](https://stackoverflow.com/questions/28798330/arrow-functions-and-this) for more about that, and [this question's answers](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) for why `this` isn't special inside an object literal. – T.J. Crowder Jul 09 '21 at 13:21
  • See [How does the “this” keyword work?](/q/3127429/4642212). – Sebastian Simon Jul 09 '21 at 13:24

0 Answers0