[英]How to use javascript object function to return a value and use it as object property.?
在銷售價格中,我希望通過將 MRP 和折扣作為 arguments 傳遞給 function get_selling_price 獲得 1000-20%,即 800,但我的代碼給出錯誤 get_selling_price undefined get_selling_price。 請幫助我修復它並讓我知道為什么會這樣,因為我在使用它之前聲明了 function。
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);
在 JavaScript 中,如果要從 object 方法訪問 object 內部存儲的信息,則需要使用常規function()而不是箭頭 function 。 在您的情況下,要訪問 Sock object 的 selling_price中的 get_selling_price function,您需要將 selling_price 定義為常規 function 並使用此關鍵字訪問 object 的另一個函數/屬性(參見下面的示例)。
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}`);
},
};
另外,順便提一下,我建議您在 JavaScript 中使用此關鍵字進行確認,您可以參考此文檔: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.