Clarification on "this" usage -- Bleep Bleep


#1


https://www.codecademy.com/courses/close-the-super-makert/0/5?curriculum_id=506324b3a7dffd00020bf661


I'm a little confused as to when "this" is necessary. My code runs correctly as is posted, but I see some people use this.lastTransactionAmount. I see that unless I replace both instances with the "this" version or have both without it, the output is incorrect. Why is this so?


var cashRegister = {
    total:0,
    lastTransactionAmount:0,
    //Dont forget to add your property
    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;
    },
    //Add the voidLastTransaction Method here
    voidLastTransaction: function() {
        this.total -= lastTransactionAmount;
    }
    
};

cashRegister.scan('eggs',1);
cashRegister.scan('milk',1);
cashRegister.scan('magazine',1);
cashRegister.scan('chocolate',4);

//Void the last transaction and then add 3 instead
cashRegister.voidLastTransaction();
cashRegister.scan('chocolate',3);

//Show the total bill
console.log('Your bill is '+cashRegister.total);


#2

The this keyword refers to and holds the value of an object passed by it. Most of the time you will find it in an object or a method as you have seen here,

this line here,

this.total -= lastTransactionAmount;

subtracts from the cashRegisters total from the lastTransactionAmount.

But that operation only occurs when it is called,


#3

So in this.total, this refers to cashRegister, yes? So why does the code work without lastTransactionAmount specified with a "this" keyword? Is the interpreter declaring for me a "lastTransactionAmount" variable when I don't?


#4

No when you were creating the cashRegister object you set lastTransactionAmount to 0, then in your add method you set it equal to itemCost.

So your voidLastTransaction method basically set it back to 0. :slight_smile:


#5

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