汉堡包辅以一个或多个stuffing(不少于1个)。
但是,当我使用...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());

最佳答案

您不能像以前那样使用箭头功能,而需要使用旧的function声明(或也使用es6 class语法糖)。看一下this answer以了解原因(在您的情况下,不是获得Hamburger对象,而是获得全局window对象)。
不要在humb1的实现上使用calculatePrice,该实现是类原型的一部分,而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());

09-25 16:26