gpt4 book ai didi

javascript - 将函数返回值分配给Javascript函数中的值

转载 作者:行者123 更新时间:2023-12-03 02:40:48 26 4
gpt4 key购买 nike

这是我遇到的问题的简化示例。

function Part(price, qty) {
this.price = price;
this.qty = qty;
this.value = function() {
return this.price * this.qty
}
}

var fancyPart = new Part(2, 3);


console.log(fancyPart.value)

我希望打印 6到控制台,而是打印:

function () {
return this.price * this.qty
}

为什么会发生这种情况?

我正在尝试使用它来创建一个“对象”,并且正在阅读这个问题的各种方法:Which way is best for creating an object in javascript? is "var" necessary before variable of object?

最佳答案

您可以使用类语法并添加作为 getter :

class Part {
constructor (price, qty) {
this.price = price;
this.qty = qty;
};

// Implement value as a getter
get value() {
return this.price * this.qty
};

}

var fancyPart = new Part(2, 3);

// No need for parameter list
console.log(fancyPart.value)

关于javascript - 将函数返回值分配给Javascript函数中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48332670/

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