MST

星途 面试题库

面试题:TypeScript中利用构造函数一次性构建复杂继承关系的对象

在TypeScript中,有一个基类`Animal`,具有`name`属性和`speak`方法。然后有两个子类`Dog`和`Cat`继承自`Animal`,`Dog`有`bark`方法,`Cat`有`meow`方法。请编写代码,使用构造函数一次性构建`Dog`和`Cat`对象,并展示如何调用它们各自的方法和继承自基类的方法。
16.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

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

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

class Cat extends Animal {
    constructor(name: string) {
        super(name);
    }
    meow() {
        console.log(`${this.name} meows.`);
    }
}

// 使用构造函数构建对象
const myDog = new Dog('Buddy');
const myCat = new Cat('Whiskers');

// 调用各自的方法和继承自基类的方法
myDog.speak(); 
myDog.bark(); 
myCat.speak(); 
myCat.meow();