汉堡包辅以一个或多个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());
答案 0 :(得分:3)
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());