0

please, I have a doub Why with arrow function inside in a object doesn't work? How we do to can make it works with arrow function?

let person = {
  name: "Homer Simpson",
  birdYear: 2000,
  getAge: function() { // WORKS!
    return 2020 - this.birdYear
  },
  getAgeWithArrowF: () => { // Doesn't works
    return 2020 - this.birdYear // using person.birdYear wrks but i need with (this.birdYear)
    // cant reach birdYear =(
  }
};

// The call

console.log(person.getAge()); // 2020
console.log(person.getAgeWithArrowF()); // NaN

THANKS!

RobG
  • 124,520
  • 28
  • 153
  • 188
Nube Nube
  • 37
  • 4
  • 4
    "How we do to can make it works with arrow function?" — You can't. Use the right tool for the job. – Quentin Jan 07 '21 at 13:31
  • The fat arrow transfers the context the object belongs to inside the function. On the other hand, `function()` transfers the object's own context inside the function. – Jeremy Thille Jan 07 '21 at 13:33
  • *this* in a function expression (first example) is set by the call. If it's called as `person.getAge()`, *this* will be *person*. But *this* in an arrow function (second example) is inherited from the enclosing execution context. Since it's global code, it will be the global object. – RobG Jan 07 '21 at 13:36
  • 1
    @JeremyThille—arrow functions have their own execution context (otherwise variables would be inherited too), only their *this* is from the enclosing context. – RobG Jan 07 '21 at 13:38

0 Answers0