public
- 使用场景:
public
修饰符是最宽松的访问级别,类的所有实例都可以访问该属性或方法,在类外部也能直接访问。常用于需要在类的外部被广泛调用和访问的成员。
- 示例:
class Animal {
public name: string;
public constructor(name: string) {
this.name = name;
}
public sayHello(): void {
console.log(`Hello, I'm ${this.name}`);
}
}
const dog = new Animal('Buddy');
dog.sayHello(); // 可以在类外部直接调用
console.log(dog.name); // 可以在类外部直接访问属性
private
- 使用场景:
private
修饰符表示私有成员,只能在类的内部访问,子类也无法访问。用于封装一些不希望外部直接访问和修改的数据或方法,保护类的内部实现细节。
- 示例:
class BankAccount {
private balance: number;
public constructor(initialBalance: number) {
this.balance = initialBalance;
}
private updateBalance(amount: number): void {
this.balance += amount;
}
public deposit(amount: number): void {
this.updateBalance(amount);
console.log(`Deposited ${amount}. New balance: ${this.balance}`);
}
}
const account = new BankAccount(100);
// account.balance; // 报错,无法在类外部访问
// account.updateBalance(50); // 报错,无法在类外部访问
account.deposit(50);
protected
- 使用场景:
protected
修饰符表示受保护成员,只能在类内部和子类中访问,在类外部无法访问。适用于希望在类的继承体系内共享,但又不想暴露给外部的成员。
- 示例:
class Shape {
protected color: string;
public constructor(color: string) {
this.color = color;
}
protected getColor(): string {
return this.color;
}
}
class Circle extends Shape {
private radius: number;
public constructor(color: string, radius: number) {
super(color);
this.radius = radius;
}
public describe(): void {
console.log(`This is a ${this.getColor()} circle with radius ${this.radius}`);
}
}
const circle = new Circle('red', 5);
// circle.color; // 报错,无法在类外部访问
// circle.getColor(); // 报错,无法在类外部访问
circle.describe();