2014-09-30 109 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);