簡體   English   中英

購物車類 JavaScript

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM