嗨,我正在编写一个简单的模块函数,用于计算餐馆账单,但是我的总金额未总计,我想这是因为this关键字
//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 +税+小费= 200 + 26 + 20 = 246,但我不断得到252,这意味着我得到200+ 26 + 26,这没有任何意义。有人可以详细说明吗?
您需要在同一个构造函数中传递两个值,像这样
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句