3/7 "ReferenceError: total is not defined" but it is?


#1

I keep getting this error
"ReferenceError: total is not defined"
but it looks defined to me? Can anyone help? Thanks in advance! :smile:


var cashRegister = {
total: 0,
//insert the add method here
add: function(itemCost) {
total += itemCost;
},

scan: function (item) {
    switch (item) { 
    case "eggs": 
        this.add(0.98); 
        break;

    case "milk": 
        this.add(1.23); 
        break;

    //Add other 2 items here
    case "magazine":
        this.add(4.99);
        break;

    case "chocolate":
        this.add(0.45);
        break;

    }
    return true;
}

};

//Scan 2 eggs and 3 magazines
cashRegister.scan("eggs");
cashRegister.scan("eggs");
cashRegister.scan("magazine");
cashRegister.scan("magazine");
cashRegister.scan("magazine");
//Show the total bill
console.log('Your bill is '+ cashRegister.total);


#2

When you're calling a variable that isn't defined in the function it has to be called from its source "this.total" instead of total, since the variable isn't defined as a global variable. It's hard to fully explain but change the "total += itemCost;" to

this.total += itemCost;

#3

Beat me in seconds with this answer. Anyway, not sure if I could have came up with better explanation. Sounds alright to me, and it works.