我创建了两个类,jsCart代表一个店铺的购物车,jsProduct代表一个产品。
jsCart应该有一个对象作为属性来存储jsProduct实例。
我的问题是如何将jsProduct实例添加到jsCart的那个对象属性中。
这是jsCart(相关位)
class jsCart {
constructor() {
this.products = {};
this.sum = 0;
}
set _products(product) {
this.products[product.id] = product;
}
remove(id) {
delete this.products[id];
}
updateSum() {
for (var product in this.products) {
this.sum += this.products[product]['sum'];
}
}
}
和jsProduct(相关位)。
class jsProduct {
constructor(id, price, quantity) {
this.id = id;
this.price = price;
this.quantity = quantity;
this.sum = this.price * this.quantity;
}
set _quantity(n) {
this.quantity = n;
this.sum = this.price * this.quantity;
}
}
还有我试图将一个产品添加到购物车中的尝试。
jsCart._products = new jsProduct('bananas',23,1);
这看起来确实有效,但当我尝试添加另一个产品时,如果我正确使用chrome的控制台,它似乎会覆盖第一个产品。
也许我应该使用getter来查看.products的内容? 或者是关于setter的问题,或者是我如何使用它?
谢谢你的帮助
解决方案:
我只需要做一个名为addItem的方法,然后将项目添加到 “购物车 “中,而不是像你现在这样做。
class jsCart {
constructor() {
this.products = {};
this.sum = 0;
}
//You don't really need this
//set _products(product) {
// this.products[product.id] = product;
//}
//This should work
addProduct(product){
this.products[product.id] = product;
}
remove(id) {
delete this.products[id];
}
updateSum() {
for (var product in this.products) {
this.sum += this.products[product]['sum'];
}
}
}
cart.addProduct(...);
本文来自投稿,不代表运维实战侠立场,如若转载,请注明出处:https://www.shizhanxia.com/483.html