Mi aplicación de prueba está casi completa, sin embargo, cuando elimino una "manzana" del carrito y la cantidad cambia a 2, parece que no puedo cambiar el precio/cantidad total de lo que es cuando son tres manzanas.
Esto puede tener que ver con la clase de constructor, pero todavía soy relativamente nuevo en su uso, por lo que tengo algunos problemas para implementar una solución para esto.
En el registro de la consola, esencialmente quiero que la cantidad total refleje la cantidad de manzanas (que ahora es 2).
module.exports = { shoppingCart: function () { //create empty cart array theCart = []; // create two seperate versions of the same kind of object using class method class Fruits { constructor(fruit, price, quantity) { this.fruit = fruit; this.quantity = quantity; this.price = price * quantity--; } } let fruit1 = new Fruits("Apple", 4.95, 3); // create new object. sets the value of this if (fruit1.quantity === 3) { fruit1.quantity--; } let bothFruits = [fruit1]; //add items to the cart Array.prototype.push.apply(theCart, bothFruits); let total = fruit1.price + " = total amount."; //function to add items to the cart function removeAllItems() { if (theCart.length = !0) { theCart = []; } } //removeAllItems(); console.log(theCart, total); } }Es mejor definir price como precio unitario, no como precio total. Puede agregar más propiedades, por ejemplo, el cost como el precio total de la clase de fruta. Luego puede agregar un método para cambiar la cantidad de la fruta.
module.exports = { shoppingCart: function () { //create empty cart array theCart = []; // create two seperate versions of the same kind of object using class method class Fruits { constructor(fruit, price, quantity) { this.fruit = fruit; this.quantity = quantity; this.price = price; this.cost = quantity * price; } // add method to change fruit quantity changeQuantity(newQuantity) { this.quantity = newQuantity this.cost = this.price * newQuantity; } } let fruit1 = new Fruits("Apple", 4.95, 3); // create new object. sets the value of this if (fruit1.quantity === 3) { fruit1.quantity--; fruit1.changeQuantity(fruit1.quantity); // call the method to change the quantity } let bothFruits = [fruit1]; //add items to the cart Array.prototype.push.apply(theCart, bothFruits); let total = fruit1.cost + " = total amount."; //function to add items to the cart function removeAllItems() { if (theCart.length = !0) { theCart = []; } } //removeAllItems(); console.log(theCart, total); } }resultado
[ Fruits { fruit: 'Apple', quantity: 2, price: 4.95, cost: 9.9 } ] 9.9 = total amount.