如果在子类中写了构造函数,在子类构造函数中必须对父类的构造函数进行调用
class Animal{
name: string;
constructor(name: string){
this.name = name
}
sayHello(){
console.log('Hello World');
}
}
class Cat extends Animal{
age: number
constructor(name:string, age: number){
super(name); // 这里调用父类的构造函数
this.age = age;
}
sayHello(): void {
super.sayHello(); // 在类方法中super表示当前类的父类
}
}
const cat = new Cat('tom', 12);
console.log(`I'm ${cat.name}, I'm ${cat.age} years old.`); //I'm tom, I'm 12 years old.
cat.sayHello(); // 'Hello World'