MST

星途 面试题库

面试题:TypeScript类中访问修饰符的作用及使用场景

请详细阐述TypeScript类中public、private和protected这三种访问修饰符的作用,并分别举例说明它们在实际开发中的使用场景。
45.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

1. public访问修饰符

  • 作用public是TypeScript中类成员(属性和方法)的默认访问修饰符,表示该成员可以在类的内部、子类以及类的实例外部被访问。
  • 示例
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(); // 输出: Hello, I'm Buddy
console.log(dog.name); // 输出: Buddy
  • 实际场景:在大多数情况下,当你希望类的属性或方法能够被外部代码自由访问和调用时,使用public修饰符。例如,定义一个数据模型类,其属性可能需要被其他模块读取和修改,或者定义一个工具类,其方法需要被广泛调用。

2. private访问修饰符

  • 作用private修饰的类成员只能在类的内部被访问,子类和类的实例外部都无法访问。这有助于隐藏类的内部实现细节,防止外部代码直接修改内部状态。
  • 示例
class BankAccount {
    private balance: number;
    constructor(initialBalance: number) {
        this.balance = initialBalance;
    }
    public deposit(amount: number): void {
        if (amount > 0) {
            this.balance += amount;
        }
    }
    public getBalance(): number {
        return this.balance;
    }
}

const account = new BankAccount(100);
// console.log(account.balance); // 报错,无法在类外部访问private属性
account.deposit(50);
console.log(account.getBalance()); // 输出: 150
  • 实际场景:当你有一些不希望外部直接访问的内部状态或实现逻辑时,使用private修饰符。比如银行账户类中的余额属性,外部不应该直接修改余额,而应该通过存款、取款等方法来间接操作。

3. protected访问修饰符

  • 作用protected修饰的类成员可以在类的内部以及子类中被访问,但不能在类的实例外部被访问。它介于publicprivate之间,为子类提供了对父类部分成员的访问权限,同时保护这些成员不被外部直接访问。
  • 示例
class Shape {
    protected color: string;
    constructor(color: string) {
        this.color = color;
    }
    protected getColor(): string {
        return this.color;
    }
}

class Circle extends Shape {
    private radius: number;
    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);
// console.log(circle.color); // 报错,无法在类外部访问protected属性
// console.log(circle.getColor()); // 报错,无法在类外部访问protected方法
circle.describe(); // 输出: This is a red circle with radius 5
  • 实际场景:当你希望父类的某些属性或方法对子类可见,但对外部代码隐藏时,使用protected修饰符。例如,在图形绘制的继承体系中,父类Shape的一些属性或方法可能只需要被子类(如CircleRectangle等)使用,而不需要暴露给外部。