Short-term memory - Getting this error "ReferenceError: total is not defined"


#1


3. Short-term Memory
Write the add method which has a single parameter, itemCost. It will add the itemCost to the total.
We have partially written the scan method for you and started a switch statement. Add the following 2 items to the switch statement:
"magazine", 4.99
"chocolate", 0.45
Finally, use the scan method to buy "eggs" twice and a "magazine" three times.

I checked my code, everything seems right but i keep getting that error - "ReferenceError: total is not defined"
I need help


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
for (i=0;i<2;i++){
cashRegister.scan("eggs");
}

for (i=0;i<3;i++) {
cashRegister.scan("magazine");
}
//Show the total bill
console.log('Your bill is '+cashRegister.total);


#2

The above is looking up the scope chain to a global variable that does not exist.

The variable that does exist is in the context of an owner object, so when a method accesses it, it looks to the this object to find it.

this.total += ...

#3

here:

total += itemCost;

total is a member variable, to access member variables we need to this.memberVariableName


#4

Oh!! Thanks, I changed it to

this.total += itemCost;

Works :slight_smile:


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.