MST

星途 面试题库

面试题:TypeScript 类和继承中的访问修饰符

在TypeScript中,类的访问修饰符有哪些?请举例说明`public`、`private`和`protected`修饰符在类和继承场景下的使用及区别。
16.4万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

在TypeScript中,类的访问修饰符有public(公共的)、private(私有的)和protected(受保护的)。

public修饰符

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(); // 输出: Hello, I'm Buddy

private修饰符

使用private修饰的属性或方法,只能在类的内部访问,类的实例和子类都无法访问。

class Secret {
    private message: string;
    constructor(message: string) {
        this.message = message;
    }
    private showSecret(): void {
        console.log(`The secret is: ${this.message}`);
    }
    public revealSecret(): void {
        this.showSecret();
    }
}

let secret = new Secret('Some confidential data');
// secret.showSecret(); // 报错: 'showSecret' 是私有的,只能在类 'Secret' 内部访问。
secret.revealSecret(); // 输出: The secret is: Some confidential data

protected修饰符

使用protected修饰的属性或方法,能在类的内部以及子类中访问,但不能通过类的实例访问。

class Shape {
    protected color: string;
    constructor(color: string) {
        this.color = color;
    }
    protected describe(): void {
        console.log(`This shape is ${this.color}`);
    }
}

class Circle extends Shape {
    constructor(color: string) {
        super(color);
    }
    public draw(): void {
        this.describe();
        console.log('It is a circle.');
    }
}

let circle = new Circle('red');
// circle.describe(); // 报错: 'describe' 是受保护的,只能在类 'Shape' 及其子类中访问。
circle.draw(); 
// 输出: This shape is red
//       It is a circle.

区别总结:

  • public:完全公开,随处可访问。
  • private:仅类内部可访问,实例和子类都不行。
  • protected:类内部和子类可访问,实例不可访问。