gpt4 book ai didi

javascript - 如何对使用构造函数创建的 JavaScript 对象方法执行加法

转载 作者:行者123 更新时间:2023-12-02 19:21:42 25 4
gpt4 key购买 nike

在下面的代码中我创建了一个构造函数。我想添加两个对象的名为 total 的值(一个称为 candy ,另一个称为 computer )。他们显然不会添加......他们连接。但是,当我执行乘法时,它会按预期乘法。我需要做什么才能对它们进行加法?

代码如下。在我的示例中,我使用乘法并评论了有问题的区域。

<!DOCTYPE html> 
<meta charset="UTF-8">
<title>checkoutTemplate</title>

<script>
function Item (item,price,tax,addedFee,total){
this.item = item;
this.price = price;
this.tax = function () {
if (typeof tax == 'undefined')
{
tax = price * .10;
}
else {
tax = 0;
}
return tax;
};

this.addedFee = function () {
if (typeof addedFee == 'undefined')
{
addedFee = price * .05;
}
else {
addedFee = 0;
}
return addedFee;
};


this.total = function () {return this.price+ this.tax()+ this.addedFee()};


};



var computer = new Item("computer", 1000,"NA","NA");
var candy = new Item("candy", 0.50,"NA","NA");


document.write( "the total output value: " + candy.total() * computer.total() ); // Troubled area. I want to add candy.total and computer.total.Not multiply.

非常感谢

最佳答案

使用()让数字加法先执行:

"the total output value: " + (candy.total() + computer.total())

关于javascript - 如何对使用构造函数创建的 JavaScript 对象方法执行加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12469553/

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