In selling price I expect to get 1000-20% i.e. 800 by passing MRP and discount as arguments to the function get_selling_price, but my code gives error get_selling_price undefined get_selling_price. Please help me to fix it and let me know why this happened, since I declared the function before using it.
let Sock = {
brand: 'JS',
color: 'Red',
size: "extra-extra small",
MRP: 1000,
discount: 20,
get_selling_price: (MRP, discount)=>{return MRP-((MRP*discount)/100)},
selling_price: get_selling_price(this.MRP, this.discount),
buy: ()=>console.log(`You are buying ${this.brand}`),
sell: function(){console.log(`You are selling ${this.brand}`)},
}
console.log(Sock);
In JavaScript, if you want to access the information stored inside the object from the object method, you need to use regular function() instead of arrow function. In your case, to access the get_selling_price function inside selling_price of the Sock object, you need to define selling_price as a regular function and access another function/property of the object using this keyword (see sample below).
let Sock = {
brand: "JS",
color: "Red",
size: "extra-extra small",
MRP: 1000,
discount: 20,
get_selling_price: (MRP, discount) => {
return MRP - (MRP * discount) / 100;
},
selling_price: function () {
return this.get_selling_price(this.MRP, this.discount);
},
buy: () => console.log(`You are buying ${this.brand}`),
sell: function () {
console.log(`You are selling ${this.brand}`);
},
};
Also, just to mention, I recommend you get acknowledged with this keyword in JavaScript, you can refer to this documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this