您好我正在寫一個簡單的模塊函數,計算餐飲賬單,但我總金額不加入了,我假定這是因爲此關鍵字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,這並沒有使得感覺。任何人都可以詳細說明這個嗎?
如果是調用了'Calculator'函數的代碼? – jgillich 2014-09-30 13:22:15
你爲什麼要創建兩個不同的計算器? – kapa 2014-09-30 13:22:55
我很困惑;你有兩個計算器,在每個計算器中你都將這兩個比率設置爲相同的百分比,並且不向我們展示如何使用計算「不正確」答案的代碼。我猜它正在做你剛剛告訴它的內容。 – 2014-09-30 13:23:39