MST

星途 面试题库

面试题:TypeScript 中类的继承属性访问控制

在 TypeScript 中,定义一个基类 `Animal` 有一个受保护的属性 `name` 和一个公有方法 `speak`,再定义一个子类 `Dog` 继承自 `Animal`,在 `Dog` 类的实例方法中访问 `name` 属性并调用 `speak` 方法,最后创建 `Dog` 类的实例并执行相应操作,写出完整代码。
32.6万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
class Animal {
    protected name: string;
    constructor(name: string) {
        this.name = name;
    }
    speak() {
        console.log(`The animal ${this.name} makes a sound.`);
    }
}

class Dog extends Animal {
    constructor(name: string) {
        super(name);
    }
    bark() {
        console.log(`Dog ${this.name} is barking.`);
        this.speak();
    }
}

const myDog = new Dog('Buddy');
myDog.bark();