MST

星途 面试题库

面试题:TypeScript中extends关键字在类继承里的常见用法

请使用TypeScript编写一个简单的类继承示例,父类有一个公共属性和一个公共方法,子类继承父类并添加一个新方法,同时展示如何在子类中调用父类的方法。
42.5万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义父类
class Animal {
    // 公共属性
    name: string; 

    constructor(name: string) {
        this.name = name;
    }

    // 公共方法
    speak() {
        console.log(`${this.name} 发出声音。`);
    }
}

// 定义子类,继承自Animal
class Dog extends Animal {
    constructor(name: string) {
        super(name);
    }

    // 子类新增的方法
    bark() {
        console.log(`${this.name} 汪汪叫。`);
    }

    // 在子类中调用父类的方法
    callParentSpeak() {
        super.speak();
    }
}

// 创建子类实例
const myDog = new Dog('旺财');
myDog.bark(); 
myDog.callParentSpeak();