class Product {
// Public class field (ES2022) — mỗi instance có một bản riêng
quantity = 0;
constructor(name, price) {
this.name = name;
this.price = price;
}
// Method — nằm trên Product.prototype, dùng chung
total() {
return this.price * this.quantity;
}
// Getter / setter
get label() {
return `${this.name} (${this.price.toLocaleString("vi-VN")}đ)`;
}
set discount(percent) {
if (percent < 0 || percent > 100) throw new RangeError("0–100%");
this.price = Math.round(this.price * (1 - percent / 100));
}
// Static — gọi trên class, không trên instance
static fromJSON(json) {
const { name, price } = JSON.parse(json);
return new Product(name, price);
}
}
const p = new Product("Áo", 200_000);
p.quantity = 2;
p.total(); // 400000
p.label; // "Áo (200.000đ)" — getter dùng như thuộc tính
p.discount = 10;
p.price; // 180000
Product.fromJSON('{"name":"Quần","price":300000}');new; gọi Product() sẽ ném TypeError.typeof Product === "function" — class vẫn là hàm, method nằm trên Product.prototype.this khi truyền làm callbackclass Toggle {
on = false;
flip = () => {
this.on = !this.on;
};
}
const t = new Toggle();
button.addEventListener("click", t.flip); // this vẫn là tĐổi lại, mỗi instance có một bản hàm riêng (tốn bộ nhớ hơn method thường). Chỉ dùng khi cần truyền method đi.
const Shape = class {
[`area${"Of"}`]() { return 0; } // method tên areaOf
[Symbol.iterator]() { /* ... */ } // hay gặp: làm class thành iterable (chương 8)
};p instanceof Product; // true
Comments