Skip to content

Instantly share code, notes, and snippets.

@SomeNiceCode
Created June 16, 2025 14:47
Show Gist options
  • Save SomeNiceCode/405595f6559b97fd2f167b84403dfdfa to your computer and use it in GitHub Desktop.
Save SomeNiceCode/405595f6559b97fd2f167b84403dfdfa to your computer and use it in GitHub Desktop.
OOP JS 2
class AbstractProduct {
constructor(id, name, price, category) {
if (new.target === AbstractProduct) {
throw new Error("AbstractProduct — это абстрактный класс.");
}
this.id = id;
this.name = name;
this.price = price;
this.category = category;
}
renderCard() {
throw new Error("Нужно реализовать renderCard() в наследнике.");
}
}
class ClothingProduct extends AbstractProduct {
constructor(id, name, price, size, material) {
super(id, name, price, "Одежда");
this.size = size;
this.material = material;
}
renderCard() {
return `
<div class="product-card clothing">
<h3>${this.name}</h3>
<p>Цена: ${this.price}₽</p>
<p>Размер: ${this.size}</p>
<p>Материал: ${this.material}</p>
</div>
`;
}
}
class BookProduct extends AbstractProduct {
constructor(id, name, price, author, pages) {
super(id, name, price, "Книги");
this.author = author;
this.pages = pages;
}
renderCard() {
return `
<div class="product-card book">
<h3>${this.name}</h3>
<p>Автор: ${this.author}</p>
<p>Страниц: ${this.pages}</p>
<p>Цена: ${this.price}₽</p>
</div>
`;
}
}
class Basket {
constructor() {
this.items = []; // [{ product, quantity }]
}
addItem(product, quantity = 1) {
const existing = this.items.find(item => item.product.id === product.id);
if (existing) {
existing.quantity += quantity;
} else {
this.items.push({ product, quantity });
}
}
removeItem(productId) {
this.items = this.items.filter(item => item.product.id !== productId);
}
getTotal() {
return this.items.reduce((sum, item) =>
sum + item.product.price * item.quantity, 0);
}
render() {
if (this.items.length === 0) return "🛒 Корзина пуста.";
return this.items.map(item =>
`${item.product.name} — ${item.quantity} × ${item.product.price}₽`
).join('\n') + `\nИтого: ${this.getTotal()}₽`;
}
}
class User {
constructor(id, name, email) {
this.id = id;
this.name = name;
this.email = email;
this.basket = new Basket();
}
addToBasket(product, quantity = 1) {
this.basket.addItem(product, quantity);
}
viewBasket() {
return this.basket.render();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment