[英]shopping cart class JavaScript
i want to make a shopping cart with JavaScript, i want make a Class that called 'Cart' that have a function like this我想用 JavaScript 制作一个购物车,我想制作一个名为“Cart”的类,它具有这样的功能
addProduct (productcode, quantity)
deleteProduct (productcode)
showcart()
so far i have done this到目前为止我已经这样做了
class Cart{
constructor(productcode, quantity){
this.productcode = productcode;
this.quantity = quantity;
}
addProduct (productcode, quantity){
}
deleteProduct (productcode){
}
showcart(){
}
}
have no idea what to do next不知道接下来要做什么
this is how I would go about it , you can test the snippet这就是我要做的,你可以测试代码片段
class CartItem{ constructor(title,price, quantity){ this.title = title; this.price = price; this.quantity = quantity; this.updateQuantity.bind(this) } updateQuantity( quantity){ this.quantity +=quantity } } class Cart{ constructor(){ this.cartItems = []; this.addItem.bind(this) this.removeItem.bind(this) this.showcart.bind(this) this.checkIfItemExists.bind(this) } addItem(cartItem){ //if item s already added to cart increment its quantity const alreadyInCart=mycart.checkIfItemExists(cartItem.title) if(alreadyInCart) return cartItem.updateQuantity(cartItem.quantity) //else just add the tem this.cartItems.push(cartItem) } checkIfItemExists(title){ return this.cartItems.filter(item=> item.title == title)[0] != undefined } removeItem (title){ this.cartItems= [...this.cartItems].filter(item=>item.title !=title ) } showcart(){ console.log(this.cartItems) } } const item1 = new CartItem('item1',20,1) const item2= new CartItem('item2',20,1) const mycart = new Cart() mycart.addItem(item1) mycart.addItem(item1) mycart.addItem(item2) mycart.showcart()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.