0

I'm trying to build muscle memory by using arrow functions, but I seem to be having a conflict with using one inside of an object. Here's my code:

const gwen = {
    firstName : 'Gwen',
    lastName : 'Stacy',
    mass : 78,
    height : 1.69,

    calcBMI: function () {
        return this.mass / (this.height ** 2)
    }

}

const patrick = {
    firstName : 'Patrick',
    lastName : 'Arnolds',
    mass : 92,
    height : 1.95,

    calcBMI: () => this.mass / (this.height ** 2)

}

console.log(gwen.mass, gwen.height, gwen.calcBMI())
console.log(patrick.mass, patrick.height, patrick.calcBMI())

Output from the first object called 'gwen' uses a regular function definition:

78 1.69 27.309968138370508

Output from the second object called 'patrick' is my attempt at using an arrow function inside of an object:

92 1.95 NaN

I've looked up articles on other websites from a search, but it seems nothing has been written based on my specific issue. I'm following along with tutorials and experimentation on the side. Maybe I'm attempting to use an arrow function in the wrong context.

FrankT335
  • 11
  • 3
  • 1
    `this` deliberately behaves differently in arrow functions vs normal functions. See https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable – Nicholas Tower Jun 19 '22 at 19:55
  • You may want to use getters and setters instead. Example: const patrick = { mass : 92, height : 1.95, get calcBMI(){return this.mass / (this.height ** 2)} }; patrick.calcBMI // 24.1946... Note how we DON'T even use parantheses "()" here to call calcBMI in the end (which is a nice touch, imo). – Foxcode Jun 19 '22 at 20:18

0 Answers0