public
- 应用场景:用于类的成员(属性或方法),这些成员可以在类的内部、子类以及类的实例外部访问。通常用于需要对外暴露的接口,供其他代码使用该类的功能。
- 实际项目示例:
class User {
public name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public greet() {
return `Hello, I'm ${this.name} and I'm ${this.age} years old.`;
}
}
let user = new User('John', 30);
console.log(user.name); // 可以在类外部访问
console.log(user.greet()); // 可以在类外部调用
private
- 应用场景:用于类的成员,这些成员只能在类的内部访问。主要用于隐藏类的内部实现细节,防止外部代码直接修改或访问这些内部状态,从而遵循封装原则。
- 实际项目示例:
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
public deposit(amount: number) {
if (amount > 0) {
this.balance += amount;
}
}
public withdraw(amount: number) {
if (amount > 0 && amount <= this.balance) {
this.balance -= amount;
}
}
public getBalance() {
return this.balance;
}
}
let account = new BankAccount(1000);
// console.log(account.balance); // 报错,无法在类外部访问
account.deposit(500);
console.log(account.getBalance()); // 通过公共方法访问私有属性
protected
- 应用场景:用于类的成员,这些成员可以在类的内部以及子类中访问,但不能在类的实例外部访问。通常用于一些希望子类可以访问,但不希望外部直接访问的成员,比如一些基础的方法或属性,子类可以基于它们进行扩展。
- 实际项目示例:
class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
protected makeSound() {
return 'Some sound';
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
public bark() {
return `${this.name} says ${super.makeSound()}`;
}
}
let dog = new Dog('Buddy');
// console.log(dog.name); // 报错,无法在类外部访问
console.log(dog.bark()); // 通过子类方法间接访问 protected 成员