简体   繁体   English

如何使用 javascript object function 返回一个值并将其用作 object 属性。?

[英]How to use javascript object function to return a value and use it as object property.?

In selling price I expect to get 1000-20% ie 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.在销售价格中,我希望通过将 MRP 和折扣作为 arguments 传递给 function get_selling_price 获得 1000-20%,即 800,但我的代码给出错误 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.请帮助我修复它并让我知道为什么会这样,因为我在使用它之前声明了 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);

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 .在 JavaScript 中,如果要从 object 方法访问 object 内部存储的信息,则需要使用常规function()而不是箭头 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).在您的情况下,要访问 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}`);
  },
};

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另外,顺便提一下,我建议您在 JavaScript 中使用此关键字进行确认,您可以参考此文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM