var cashRegister = {
total:0,
add: function(itemCost){
total += this.itemCost;
},
scan: function(item) {
switch (item) {
case "eggs":
this.add(0.98);
break;
case "magazine":
this.add(4.99);
break;
}
return true;
}
};
cashRegister.scan("eggs");
cashRegister.scan("magazines");
console.log('Your bill is '+cashRegister.total);
输出显示NAN,并且total未定义。我在add方法中尝试了cashRegister.total
和this.total
,没有运气。上面的代码出了什么问题?
答案 0 :(得分:3)
您在错误的地方this
。 add
内的行应该是这样的
this.total += itemCost;
当你说
时total += this.itemCost;
total
尚未在函数this.itemCost
表示您正在使用当前对象中的元素itemCost
。但实际上并不存在。答案 1 :(得分:2)
试试这段代码:
var cashRegister = {
total:0,
add: function(itemCost){
this.total += itemCost;
},
scan: function(item) {
switch (item) {
case "eggs":
this.add(0.98);
break;
case "magazine":
this.add(4.99);
break;
}
return true;
}
};
cashRegister.scan("eggs");
cashRegister.scan("magazines");
console.log('Your bill is '+cashRegister.total);
你的错误在于这一行:
total += this.itemCost;
答案 2 :(得分:2)
将add
方法更改为:
add: function(itemCost){
this.total += itemCost; // "this" was in the wrong place
}
另外,你不应该使用浮点数来赚钱 - 它们不准确!使用整数作为美分。在您需要显示美元金额之前,请勿转换为美元。否则你可能会有不可思议的分数,随着时间的推移会增加。
var magicDollars = 1.10 + 2.20;
console.log( magicDollars ); // 3.3000000000000003 - Not good! Money can't materialize itself.
var cents = 110 + 220;
var realDollars = cents / 100;
console.log( realDollars ); // 3.3 - Better. No unexpected fractional cents.