0

我正在尝试编写一个基本功能来生产一台自动取款机。每当我运行下面的代码时,我得到的总数停留在 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并且可以对其他种类的食物重复此操作。

4

2 回答 2

3

重写 add 成为 this 的一个属性:

this.add = function (itemCost) {
  this.total = this.total + itemCost; 
}
于 2013-10-26T19:52:53.310 回答
3

“this”通常不是您认为的那样......即当您调用没有上下文(add而不是VCM.scan)的函数时,上下文将被设置为全局对象。有很多关于这个主题的文章——即理解 JavaScript 上下文

有几种选择来处理它。

一种是按照 tomca32 的建议通过将其设为“公共成员”来使用上下文调用它(请注意,它会暴露在许多情况下可能不希望出现的私有方法):

this.add = function(itemCost) { this.total += itemCost;} this.add(cost);

另一种选择是保存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到局部变量)非常常见且最容易遵循:只需selfmethat中您将使用this..

于 2013-10-26T19:56:30.557 回答