gpt4 book ai didi

javascript - js中的this关键字

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:34 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com