2014-09-30 85 views
0

您好我正在寫一個簡單的模塊函數,計算餐飲賬單,但我總金額不加入了,我假定這是因爲此關鍵字this關鍵字在JS

//Function meant to be used as a constructor 
var Calculator = function(aPercentage){ 
    this.taxRate = aPercentage; 
    this.tipRate = aPercentage; 
} 
Calculator.prototype.calcTax = 
    function(amount) {return amount*(this.taxRate)/100;} 
Calculator.prototype.calcTips = 
    function(amount) {return amount *(this.tipRate)/100;} 
Calculator.prototype.calcTotal = 
    function(amount) {return (amount + (this.calcTips(amount))+ this.calcTax(amount));} 

module.exports = Calculator; 

//This the code that calls the calculator 
var Calculator = require("./Calculator.js"); 

var taxCalculator = new Calculator(13); //13% Ontario HST 
var tipsCalculator = new Calculator(10); //10% tips 

var itemPrice = 200; //$200.00 

console.log("price: $" + itemPrice); 
console.log("tax: $" + taxCalculator.calcTax(itemPrice)); 
console.log("tip: $" + tipsCalculator.calcTips(itemPrice)); 
console.log("---------------"); 
console.log("total: $" + taxCalculator.calcTotal(itemPrice)); 

我應該的得到總價格:itemPrice + tax + tip = 200 + 26 + 20 = 246但是我一直得到252 這意味着我得到了200+ 26 + 26,這並沒有使得感覺。任何人都可以詳細說明這個嗎?

+0

如果是調用了'Calculator'函數的代碼? – jgillich 2014-09-30 13:22:15

+0

你爲什麼要創建兩個不同的計算器? – kapa 2014-09-30 13:22:55

+0

我很困惑;你有兩個計算器,在每個計算器中你都將這兩個比率設置爲相同的百分比,並且不向我們展示如何使用計算「不正確」答案的代碼。我猜它正在做你剛剛告訴它的內容。 – 2014-09-30 13:23:39

回答

4

您需要在同一個構造函數傳遞兩個值,這樣

function Calculator (taxPercentage, tipPercentage) { 
    this.taxRate = taxPercentage; 
    this.tipRate = tipPercentage; 
} 

而且你會創建一個這樣

var billCalculator = new Calculator(13, 10); 

一個對象,並調用這樣

console.log(billCalculator.calcTax(200)); 
// 20 
console.log(billCalculator.calcTips(200)); 
// 26 
console.log(billCalculator.calcTotal(200)); 
// 246 
功能
+1

擊敗我5秒! – Shaded 2014-09-30 13:23:11

+0

O,ic。現在感覺分配,哈哈感謝分配! – mvitagames 2014-09-30 13:32:12

2

您正在爲taxRatetipRate分配相同的費率。也許你想傳遞兩個不同速率的構造器:

var Calculator = function(taxRate, tipRate){ 
    this.taxRate = taxRate; 
    this.tipRate = tipRate; 
} 

然後使用它應該像代碼:

var tax = new Calculator(13, 10); 
var itemPrice = tax.calcTotal(200);