Building a Cash Register - 5/7


#1

I dont understand a lot of things in this exercise-could someone explain please?

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

1) lastTransactionAmount:0, // Is it =0 because we don't know yet what the amount of the last transaction was?
2) Why again do we use "this."?

voidLastTransaction: function() {
this.total -= this.lastTransactionAmount;
}
3) Add a method called voidLastTransaction that subtracts the last amount transacted from total.
Why don't we include it like that:
var cashRegister = {
total:0,
lastTransActionAmount:0,
add: function(itemCost) {
this.lastTransactionAmount = itemCost;
this.total += itemCost;
voidLastTransaction: function() {
this.total -= this.lastTransactionAmount;
}
},

4.
cashRegister.scan('eggs',1);
cashRegister.scan('milk',1);
cashRegister.scan('magazine',1);
cashRegister.scan('chocolate',4);
cashRegister.voidLastTransaction();
cashRegister.scan('chocolate',3);
console.log('Your bill is '+cashRegister.total);

--> the code in bold: whats the purpose of creating that voidLastTransaction if in the end we still have to write all the code, I mean we could have also changed the chocolate quantity "manually" because it would be as much code as we used now

Thanks!


#2

Thats the entire code:
var cashRegister = {
total:0,
lastTransActionAmount:0,
add: function(itemCost) {
this.lastTransactionAmount = itemCost;
this.total += 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 -= this.lastTransactionAmount;
}
};
cashRegister.scan('eggs',1);
cashRegister.scan('milk',1);
cashRegister.scan('magazine',1);
cashRegister.scan('chocolate',4);
cashRegister.voidLastTransaction();
cashRegister.scan('chocolate',3);
console.log('Your bill is '+cashRegister.total);


#3

1) lastTransactionAmount:0, // Is it =0 because we don't know yet what the amount of the last transaction was?

This is to initialize the variable. The value is arbitrary since it is set in the program at the time of each transaction.

2) Why again do we use "this."?

this is the context object, cashRegister. Inside the methods it always refers to the owner object.

add: function(itemCost){
    this.total += itemCost || 0;
}

add() is a method of the cashRegister object. this.total refers to the total property of this context.

Mull this over for a minute, and if you still need to discuss your number 3 and 4 questions, we can.