简体   繁体   English

购物车类 JavaScript

[英]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)
  • this is a function to add product and will increment the quantity if we add the same product这是添加产品的功能,如果我们添加相同的产品,则会增加数量
deleteProduct (productcode)
  • this is a function to delete the product这是一个删除产品的功能
showcart()
  • this is a function that will show the product and the quantity in the cart这是一个功能,将显示购物车中的产品和数量

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM