面试题答案
一键面试1. public(公共访问修饰符)
- 应用场景:当类的属性或方法需要在类的内部、子类以及类的实例外部都能被访问时,使用
public
。这通常用于定义类对外提供的接口,让其他代码能够操作该类的实例。 - 示例:
class Animal {
public name: string;
public constructor(name: string) {
this.name = name;
}
public sayHello(): void {
console.log(`Hello, I'm ${this.name}`);
}
}
let dog = new Animal('Buddy');
dog.sayHello(); // 可以在类的实例外部调用
console.log(dog.name); // 可以在类的实例外部访问属性
2. private(私有访问修饰符)
- 应用场景:当类的属性或方法只希望在类的内部被访问,不希望外部代码直接访问或修改时,使用
private
。这有助于隐藏类的内部实现细节,防止外部代码意外修改内部状态。 - 示例:
class BankAccount {
private balance: number;
public constructor(initialBalance: number) {
this.balance = initialBalance;
}
public deposit(amount: number): void {
if (amount > 0) {
this.balance += amount;
}
}
public getBalance(): number {
return this.balance;
}
}
let account = new BankAccount(100);
// account.balance; // 报错,无法在类的外部访问私有属性
account.deposit(50);
console.log(account.getBalance()); // 通过公共方法访问私有属性
3. 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}`);
}
}
let circle = new Circle('red', 5);
// circle.color; // 报错,无法在类的实例外部访问受保护属性
// circle.getColor(); // 报错,无法在类的实例外部访问受保护方法
circle.describe(); // 在子类方法中可以访问受保护属性和方法
合理使用实现数据封装
通过使用private
将敏感数据(如BankAccount
的余额)隐藏起来,只提供公共方法(如deposit
和getBalance
)来间接操作这些数据,从而实现数据封装。protected
用于在继承体系中,保护一些属性和方法,让子类可以基于这些保护成员进行扩展和复用,同时避免外部直接访问。public
则用于定义类对外公开的接口,让其他代码能够与类进行交互。