[英]shopping cart class JavaScript
我想用 JavaScript 制作一個購物車,我想制作一個名為“Cart”的類,它具有這樣的功能
addProduct (productcode, quantity)
deleteProduct (productcode)
showcart()
到目前為止我已經這樣做了
class Cart{
constructor(productcode, quantity){
this.productcode = productcode;
this.quantity = quantity;
}
addProduct (productcode, quantity){
}
deleteProduct (productcode){
}
showcart(){
}
}
不知道接下來要做什么
這就是我要做的,你可以測試代碼片段
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.