Cash Register 3. Short - Term Memory


#1

Hi, can you please tell me why this code doesn't work? When I try to run it, it returns this error: "Unexpected token . ". I think it's just some stupid typo, but I've spent a lot of time looking for it and can't find anything wrong.


var cashRegister = {
    this.total: 0,
    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;
        case "magazine":
            this.add(4.99);
            break;
        case "chocolate":
            this.add(0.45);
            break;
        }
        return true;
    }
};
cashRegister.scan("eggs");
cashRegister.scan("eggs");
cashRegister.scan("magazine");
cashRegister.scan("magazine");
cashRegister.scan("magazine");
console.log("Your bill is " + cashRegister.total);


#2

Run it through some other interpreter that includes line numbers. For example, I can copy your code and then run:

$ xsel -b | node  # pipe clipboard content into nodejs
[stdin]:2
    this.total: 0,
        ^
SyntaxError: Unexpected token .

#3

Thank you for your answer! Deleting "this." from line 2 solved it, but I don't really understand why it wasn't correct. Another thing i don't understand is "return true" on line 21. It was there at the beginning as a part of a code I was given, but I don't understand what it does nor why is it there.


#4

What's the this name usually used for? When is it used? What context were you using it in?
https://www.google.com/search?q=mdn+this (mdn is a good reference to js)

The return statement has no purpose whatsoever since nothing is paying any attention to what that method returns.


#5

Thank you very much, the source you provided was very helpful.


#6

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