Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object output returning NAN [duplicate]

This is my code

const products = 
      [ 
          {

    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
    "coefficient":2,
    "price": () => 2000 * this.coefficient
  },
  {

    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla",
    "coefficient":3, 
    "price": () => 2000 * this.coefficient
  },
] 

I want to return the price depends on the coefficient, but when i excute

products[0].price() // return NaN

how can i fix that ?

Thanks.

like image 604
Khaled Ayed -ngCode- Avatar asked Dec 03 '22 10:12

Khaled Ayed -ngCode-


1 Answers

This is due to the way that arrow functions handle the this scope. In this case, replacing the arrow function (() => this.something) with a traditional JS function (function() { return this.something; }) will solve your problem.

like image 179
Haroldo_OK Avatar answered Dec 24 '22 06:12

Haroldo_OK