我正在尝试编写基本功能以生产自动取款机。每当我运行下面的代码时,我总得到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);
当我实现add函数时,似乎出现了问题。我的理由是,在这个例子中,一旦我找到了3个鸡蛋的总成本,我就将这个数量加到this.total
,并且可以为其他类型的食物重复这个。
答案 0 :(得分:3)
重写add为此属性:
this.add = function (itemCost) {
this.total = this.total + itemCost;
}
答案 1 :(得分:3)
“这个”通常不是你认为的...... I.e.当您在没有上下文(add
而不是VCM.scan
)的情况下调用函数时,上下文将被设置为全局对象。有很多关于这个主题的文章 - 即Understanding JavaScript Context。
有几种方法可以解决它。
一种是通过将其作为tomca32建议的“公共成员”来调用上下文(请注意,它将公开私有方法,这在许多情况下可能是不可取的):
this.add = function(itemCost){this.total + = itemCost;} this.add(成本);
另一种选择是将this
保存到本地变量中,以便您知道您正在使用的是什么:
function VirtualCashMachine(){
var self = this;
....
function add(itemCost){
self.total = self.total + itemCost;
};
或者您可以使用function.call
显式传递上下文:
function add(itemCost) { this.total += itemCost;}
add.call(this, cost);
或者您可以完全避免本地函数中的this
,但是您需要使用get / set方法公开属性。在这种情况下,因为函数将看到父范围内的所有局部变量,它可以正确地修改总数:
var total = 0;
this.getTotal() { return total;}
function add(itemCost) { total += itemCost;}
第二种方法(将this
复制到本地变量)在我看来非常常见且最容易理解:只需使用self
(或其他常用的me
或{{1}在你班级里的任何地方,你都会使用that
。