Reputation: 597
I'm learning JavaScript objects and have one question regarding the code below: the object "cashRegister" has only 1 method "add()". Then, outside the object there is another method "scan()". How is it possible at the end of the code to invoke "cashRegister.scan()" if the "scan" method does not belong to the "cachRegister" object? Is it because "scan()" uses "add()" method which belongs to "cashRegister" and that usage makes "scan()" the method of "cashRegister" or what?
var cashRegister = {
total:0,
add: function(itemCost){
this.total += itemCost;
},
scan: function(item, quantity) {
switch (item) {
case "A": this.add(0.98 * quantity); break;
case "B": this.add(1.23 * quantity); break;
case "C": this.add(4.99 * quantity); break;
case "D": this.add(0.45 * quantity); break;
}
}
};
// scan each item 4 times
cashRegister.scan("A", 4);
cashRegister.scan("B", 2);
cashRegister.scan("C", 4);
cashRegister.scan("D", 3);
//Show the total bill
console.log('Your bill is '+cashRegister.total);
Upvotes: 0
Views: 178
Reputation: 555
In the given code scan method is actually inside the cashRegister object and as this is a method of object "cashRegister", we can invoke like "cashRegister.scan()". Otherwise this will give error. And in the given code error will come on calling "this.add()" method also if "scan()" method will be outside the cashRegister object.
Upvotes: 2
Reputation: 318
scan method belongs to cashregister. Here's the code reformated a bit, so you can see it:
var cashRegister =
{
total:0,
add: function(itemCost)
{
this.total += itemCost;
},
scan: function(item, quantity)
{
switch (item)
{
case "A": this.add(0.98 * quantity); break;
case "B": this.add(1.23 * quantity); break;
case "C": this.add(4.99 * quantity); break;
case "D": this.add(0.45 * quantity); break;
}
}
};
// scan each item 4 times
cashRegister.scan("A", 4);
cashRegister.scan("B", 2);
cashRegister.scan("C", 4);
cashRegister.scan("D", 3);
//Show the total bill
console.log('Your bill is '+cashRegister.total);
Upvotes: 1
Reputation: 182
In your code, the scan
method is actually inside the cashRegister
object.
Upvotes: 1