📝 public(默认)
class User {
// public 是默认值,可省略
public name: string;
age: number; // 省略时默认为 public
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const user = new User('Alice', 30);
console.log(user.name); // OK: public 可外部访问
console.log(user.age); // OK
🔒 private
class BankAccount {
private balance: number = 0;
deposit(amount: number): void {
this.balance += amount;
}
withdraw(amount: number): boolean {
if (amount <= this.balance) {
this.balance -= amount;
return true;
}
return false;
}
getBalance(): number {
return this.balance;
}
}
const account = new BankAccount();
account.deposit(1000);
// account.balance; // Error: private 不可外部访问
console.log(account.getBalance()); // OK: 通过公共方法访问
🛡️ protected
class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
protected makeSound(): void {
console.log(`${this.name} makes a sound`);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
bark(): void {
this.makeSound(); // OK: protected 可在子类访问
console.log(`${this.name} barks`); // OK
}
}
const dog = new Dog('Buddy');
// dog.name; // Error: protected 不可外部访问
dog.bark(); // OK
#️⃣ JavaScript 私有字段
// ES2022+ 私有字段语法
class User {
#password: string; // 真正的私有字段
constructor(name: string, password: string) {
this.name = name;
this.#password = password;
}
verifyPassword(input: string): boolean {
return this.#password === input;
}
}
const user = new User('Alice', 'secret');
// user.#password; // Error: 语法错误
// user['#password']; // Error: 无法访问
💡
private vs #字段
TypeScript 的 private 是编译时检查,编译后可通过属性访问;# 字段是 JavaScript 原生私有字段,运行时也无法访问。