Reputation: 633
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);
the output show NAN, and total is undefined. I tried cashRegister.total
and this.total
in the add method, no luck. What's wrong with the code above?
Upvotes: 0
Views: 54
Reputation: 7680
Change the add
method to:
add: function(itemCost){
this.total += itemCost; // "this" was in the wrong place
}
Also, you shouldn't ever use floating-point numbers for money - they're not accurate! Use integers as cents instead. Don't convert to dollars until you need to display the dollar amount. Otherwise you might have magical fractions of cents which can add up over time.
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.
Upvotes: 2
Reputation: 239443
You have this
at wrong place. The line inside add
should have been like this
this.total += itemCost;
When you say
total += this.itemCost;
total
is not defined yet within the functionthis.itemCost
means that you are using the element itemCost
which is in the current object. But that is actually not there.Upvotes: 3
Reputation: 3232
Try this code:
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);
Your mistake was at this line:
total += this.itemCost;
Upvotes: 2