0

I have thought this would points to the object person but it actually points to an empty object. Can anyone explain?

var person = {
    name: 'James',
    birthYear: '1991',
    getAge: () => new Date().getFullYear() - this.birthYear // this points to an empty object here. test in nodejs.
}
  • Possible duplicate of [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – 4castle May 06 '17 at 17:15
  • Arrow functions don't bind `this` in the same way as normal functions. See the duplicate. – 4castle May 06 '17 at 17:18

1 Answers1

0

if you use arrow functions you are refering to the global 'this'.

this:

getAge: () => new Date().getFullYear() - this.birthYear

is different from this:

getAge: function() {
          new Date().getFullYear() - this.birthYear
        }

have a look here: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Functions_and_function_scope/Arrow_functions

Paolo
  • 704
  • 9
  • 24