js中的this关键字

时间:2014-09-30 13:18:48

标签: javascript node.js

您好我正在编写一个简单的模块函数来计算一个restaurent账单,但我的总金额并没有加起来,我假设它是因为这个关键字

//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而且没有成功。有人可以详细说明吗?

2 个答案:

答案 0 :(得分: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 :(得分:2)

您为taxRatetipRate分配相同的费率。也许你想将两种不同的速率传递给构造函数:

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

然后使用它的代码应如下所示:

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