2013-12-15 35 views
0
var cashRegister = { 
    total:0, 

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

    scan: function(item) { 
     switch (item) { 
     case "eggs": 
      this.add(0.98); 
      break; 

     case "magazine": 
      this.add(4.99); 
      break; 

     } 
     return true; 
    } 
}; 

cashRegister.scan("eggs");  
cashRegister.scan("magazines"); 

console.log('Your bill is '+cashRegister.total); 

輸出顯示NAN,總計未定義。我在添加方法中嘗試了cashRegister.totalthis.total,沒有運氣。上面的代碼有什麼問題?對象變量在javascript中不可訪問

回答

3

你在錯誤的地方有this。內add行應該是這樣的

this.total += itemCost; 

當你說

total += this.itemCost; 
  1. total沒有功能
  2. this.itemCost內尚未定義意味着你正在使用的元素itemCost這是在當前對象中。但那實際上並不存在。
2

試試這個代碼:

var cashRegister = { 
    total:0, 

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

    scan: function(item) { 
     switch (item) { 
     case "eggs": 
      this.add(0.98); 
      break; 

     case "magazine": 
      this.add(4.99); 
      break; 

     } 
     return true; 
    } 
}; 

cashRegister.scan("eggs");  
cashRegister.scan("magazines"); 

console.log('Your bill is '+cashRegister.total); 

你的錯誤是在這一行:

total += this.itemCost; 
2

更改add方法:

add: function(itemCost){ 
    this.total += itemCost; // "this" was in the wrong place 
} 

而且,你不應該永遠使用浮點數的錢 - 他們是不準確的!改爲使用整數作爲分。在您需要顯示美元金額之前,不要轉換爲美元。否則,你可能會有不可思議的分數,隨着時間的推移可能會加起來。

var magicDollars = 1.10 + 2.20; 
console.log(magicDollars); // 3.3000000000000003 - Not good! Money can't materialize itself. 

var cents = 110 + 220; 
var realDollars = cents/100; 
console.log(realDollars); // 3.3 - Better. No unexpected fractional cents.