javascript - js中的this关键字

标签 javascript node.js

您好,我正在编写一个简单的模块函数来计算餐馆账单,但我的总金额没有相加,我假设这是因为 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

关于javascript - js中的this关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26121885/

相关文章:

javascript - 如何创建一个使用随机生成的间隔调用函数的连续循环

javascript - 如何使第二列的第二行与第一列的高度相同

node.js - 在expect().toBe()上应用toBeA()方法时,它会给出一个错误,无法读取未定义的属性

node.js - POST 400(错误请求)JSON 中位置 1 处出现意外标记 o

node.js - 如何使用 Express 和 EJS 提供静态和动态内容?

javascript - post API 中的重定向错误

javascript - 我应该对对 $.ajax 的调用进行单元测试还是对已发送的 XHR 进行单元测试?

javascript - 定义返回 'undefined' 的对象的属性

javascript - CryptoJS 和 Pycrypto 协同工作

node.js - 在 dynamodb Local 中查询全局二级索引