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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With