user3057928
user3057928

Reputation: 633

object variable is unaccesible in javascript

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

Answers (3)

sbking
sbking

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

thefourtheye
thefourtheye

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;
  1. total is not defined yet within the function
  2. this.itemCost means that you are using the element itemCost which is in the current object. But that is actually not there.

Upvotes: 3

Vassilis Barzokas
Vassilis Barzokas

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

Related Questions