通过特定属性返回NaN

时间:2018-09-30 15:27:26

标签: javascript oop ecmascript-6

汉堡包辅以一个或多个stuffing(不少于一个)。
但是,当我使用...stuffing时,结果是undefined
帮助我如何纠正此任务,以便它算出所有原料的成本。

function Hamburger(size, ...stuffing) {
  this.size = size;
  this.stuffing = stuffing;
  this.topping = [];
}
Hamburger.small = {
  name: 'small',
  price: 10,
  kcal: 200
}
Hamburger.cheese = {
  name: 'cheese',
  price: 4,
  kcal: 10
}
Hamburger.meet = {
  name: 'meet',
  price: 40,
  kcal: 103
}
Hamburger.prototype.calculatePrice = () => {
  let allCost = humb1.size.price + humb1.stuffing.price;
  return `Total burger price: ${allCost}`
}

let humb1 = new Hamburger(Hamburger.small, Hamburger.cheese, Hamburger.meet);
console.log(humb1.calculatePrice());

1 个答案:

答案 0 :(得分:3)

  • 您不能像以前那样使用箭头功能,而需要使用旧的function声明(或也使用es6 class语法糖)。查看this answer以了解原因(在您的情况下,不是获得Hamburger对象,而是获得全局window对象)。
  • 请勿在{{1​​}}的实现上使用humb1calculatePrice是类原型的一部分,而humb1是类实例。
  • stuffing是一个数组。您需要处理每个项目才能获得总成本。我在这里使用了reduce

function Hamburger(size, ...stuffing) {
  this.size = size;
  this.stuffing = stuffing;
  this.topping = [];
}
Hamburger.small = {
  name: 'small',
  price: 10,
  kcal: 200
}
Hamburger.cheese = {
  name: 'cheese',
  price: 4,
  kcal: 10
}
Hamburger.meet = {
  name: 'meet',
  price: 40,
  kcal: 103
}
Hamburger.prototype.calculatePrice = function() {
  let totalCost = this.size.price + this.stuffing.reduce((a, c) => a + c.price, 0);
  return `Total burger price: ${totalCost}`;
}

let humb1 = new Hamburger(Hamburger.small, Hamburger.cheese, Hamburger.meet);
console.log(humb1.calculatePrice());