class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
class Shop extends Product {
constructor(products) {
super();
this.products = [];
}
addProduct(newProduct) {
this.products.push(newProduct);
}
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
if (productName in this.products[i]) {
this.products.splice(i, 1);
}
}
}
getAllProductNames() {
return this.products.map(object => Object.values(object)[0].name);
}
get totalProductsPrice() {
return this.products.map(object => Object.values(object)[0].price).
reduce((p, c) => p + c);
}
}
const shop = new Shop();
shop.addProduct(new Product("product 1", 1, 200));
shop.addProduct(new Product("product 1", 1, 500));
shop.addProduct(new Product("product 2", 2, 1000));
console.log(shop.totalProductsPrice);
console.log(shop.getAllProductNames());
shop.deleteProductByName("product 2");
console.log(shop.products);
https://stackoverflow.com/questions/50669392
复制相似问题