我正在尝试编写一个基本功能来生产一台自动取款机。每当我运行下面的代码时,我得到的总数停留在 0。谁能帮助我或向我解释为什么?
function VirtualCashMachine(){
//object storing food
this.food = {egg: 0.98, milk: 1.23, magazine: 4.99,chocolate: 0.45};
//total bill
this.total = 0;
//record of last transaction
this.lastTransactionAmount = 0;
//assign public methods
this.scan = scan;
this.voidLastTransaction = voidLastTransaction;
//define public methods
//add amount to total property
function scan(/*string*/item,/*integer*/ quantity){
//if food item exists in food object, find price and calculate total
if(this.food.hasOwnProperty(item)){
cost = this.food[item] * quantity;
add(cost);
this.lastTransactionAmount = cost;
}
};
function voidLastTransaction(){
this.total -= lastTransactionAmount;
};
//define private method
//add item price to total
function add(itemCost){
this.total = this.total + itemCost;
};
}
var VCM = new VirtualCashMachine();
VCM.scan("egg", 3);
console.log(VCM.total);
当我实现添加功能时,似乎出现了问题。我的理由是,一旦我在这个例子中找到了 3 个鸡蛋的总成本,我就将其添加到 中,this.total
并且可以对其他种类的食物重复此操作。