#) — ES2022Thuộc tính bắt đầu bằng # thật sự riêng tư: bên ngoài class không đọc, ghi, hay thậm chí liệt kê được.
class Account {
#balance = 0; // private field
static #count = 0; // private static field
constructor(owner) {
this.owner = owner;
Account.#count++;
}
#log(msg) { // private method
console.log(`[${this.owner}] ${msg}`);
}
deposit(amount) {
this.#balance += amount;
this.#log(`+${amount}`);
}
get balance() {
return this.#balance;
}
static get count() {
return Account.#count;
}
// Kiểm tra một object có phải Account "thật" không (ES2022: ergonomic brand check)
static isAccount(obj) {
return #balance in obj;
}
}
const a = new Account("An");
a.deposit(100);
a.balance; // 100
a.#balance; // SyntaxError — không truy cập được từ bên ngoài
Object.keys(a); // ["owner"]
Account.isAccount({ balance: 1 }); // falseTIP
Quy ước cũ _balance chỉ là "xin đừng đụng vào". #balance được ngôn ngữ đảm bảo. Dùng # trong code mới.
Chạy một lần khi class được định nghĩa, có quyền truy cập private:
class Config {
static #values;
static {
const env = globalThis.process?.env ?? {};
Config.#values = { mode: env.NODE_ENV ?? "development" };
}
static get mode() {
return Config.#values.mode;
}
}extends và superclass Shape {
constructor(name) {
this.name = name;
}
area() {
return 0;
}
toString() {
return `${this.name}: ${this.area().toFixed(2
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}Cây kế thừa sâu (3–4 tầng) rất khó sửa. Thường tốt hơn là ghép các object/hàm nhỏ:
class OrderService {
constructor({ repo, mailer }) { // nhận phụ thuộc từ ngoài vào
this.repo = repo;
this.mailer = mailer;
}
}Quy tắc: dùng extends khi quan hệ thật sự là "là một" (Circle là một Shape); còn "có một" thì dùng composition.
Comments