您好我正在写一个简单的模块函数,计算餐饮账单,但我总金额不加入了,我假定这是因为此关键字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