mvitagames
mvitagames

Reputation: 413

the this keyword in js

Hi I am writing a simple module function that calculate a restaurent bill, but my total amount is not adding up, I am assuming it's because of the this keyword

//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));

I am supposed to get total price of: itemPrice + tax + tip = 200+26+20 = 246 but i keep getting 252 which means that that I am getting 200+ 26+26 which doesnt make sence. Can anyone elaborate on this please?

Upvotes: 0

Views: 114

Answers (2)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

You're assigning the same rate to both taxRate and tipRate. Perhaps you want to pass two different rates to the constructor:

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

Then the code that uses it should look like:

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

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239453

You need to pass both the values in the same constructor, like this

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

And you would create an object like this

var billCalculator = new Calculator(13, 10);

and invoke the functions like this

console.log(billCalculator.calcTax(200));
// 20
console.log(billCalculator.calcTips(200));
// 26
console.log(billCalculator.calcTotal(200));
// 246

Upvotes: 4

Related Questions