Class: constructor, method, getter/setter và static
Khai báo class
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}');Những điều cần nhớ
- Class phải gọi bằng
new; gọiProduct()sẽ némTypeError. - Thân class luôn chạy ở strict mode.
- Class không được hoisting như function — dùng trước khi khai báo sẽ lỗi (TDZ).
typeof Product === "function"— class vẫn là hàm, method nằm trênProduct.prototype.
Class field arrow — giữ this khi truyền làm callback
class 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.
Class expression và computed method name
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)
};Kiểm tra instance
p instanceof Product; // true
Comments