5. BleepBleep: Code fails when using THIS for lastTransactionAmount


#1

Looks like this exercise expects me to use "this" but it does not work. My (working) code is:

var cashRegister = {
total:0,
lastTransactionAmount:0,

add: function(itemCost) {
    this.total +=  itemCost;
    lastTransactionAmount = itemCost;
},

scan: function(item,quantity) {
    switch (item) {
    case "eggs": this.add(0.98 * quantity); break;
    case "milk": this.add(1.23 * quantity); break;
    case "magazine": this.add(4.99 * quantity); break;
    case "chocolate": this.add(0.45 * quantity); break;
    }
    return true;
},

voidLastTransaction: function(){
    this.total -= lastTransactionAmount;
}

};

cashRegister.scan('eggs',1);
...

It took me some time to find out what was wrong. It looks like all the questions in the Q&A section point to ยจ

(method "add")
add: function(itemCost) {
this.lastTransactionAmount = itemCost;
this.total += itemCost;
},

(method "void")
voidLastTransaction: function() {
this.total -= this.lastTransactionAmount;

When I do this, lastTransactionAmount takes the value of "total" and the exercise fails. Is there some js crack who can tell me why it doesn' work for me and why?


#2

You should be using this.
Perhaps you weren't making the change in all places where you had lastTransactionAmount, so it only worked for you when you had a global variable. It should not be global. Perhaps your error message when you say it "fails" says more about what went wrong.


#3

Thanks, ionatan. This is my understanding, too. lastTransactionAmount should be local.
You were right, tough. Either working with "this.lastTransactionAmount" in both places or doing without gives the same results.

(There was no error message btw. I guess the program does only check for the resulting number (which was wrong). I did a lot of debugging with console.log so I could see that lastTransactionAmount equalled total before it was subtracted from total. Adding everything else worked fine. )