Short Term Memory - How does it work?


#1


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

My code works but I want to make sure I understand the logic behind it. Can someone please confirm or correct my understanding?

When the function "cashRegister.scan()" is run, the item passed through ("eggs" for example), runs the created "add" function from within the "scan" function to pass the price of the item into the "itemCost" parameter of the "add" function, which then runs the function adding the itemCost to the cashRegister.total.

Is this accurate?

var cashRegister = {
    total: 0,
//insert the add method here    
    add: function (itemCost) {
        this.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

so far so good, the scan method will determine which product the customer buys using a switch statement, the switch statement will call the add() method with the price of the product the customer is buying, which is added to total


#3

Thank you. That makes perfect sense, though it didn't in the beginning. There are two things that threw me off. The first was that the scan function was running the add function from within the scan function, which created kind of a chicken and the egg issue in my mind not knowing which came first.

The one that really threw me off was the use of "this.add". I was familiar with the use of "this" when creating multiple objects via a constructor, but it didn't make sense to me in this exercise and I'm still confused as to why "cashRegister.add" wasn't used as opposed to "this.add".

Do you have insight on why "cashRegister.add" couldn't have been used?


#4

but know you understand right?

cashRegister.add is used to call the add method from outside the cashRegister object. For a method to call a different method inside the object, this.methodName has to be used. Its a syntax thing


#5

I understand both now. You've been a great help. Thanks a ton!


#6

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