简述如何TypeScript中如何从子类调用基类构造函数?
参考回答
在 TypeScript 中,从子类调用基类构造函数可以通过 super 关键字实现。super 关键字用于调用父类(基类)的构造函数或方法。通常,子类需要通过 super 来初始化继承自基类的属性。调用 super 时,必须在子类构造函数的第一行。
详细讲解与拓展
- 子类调用基类构造函数:
- 子类的构造函数可以使用
super()来调用基类的构造函数,并传递必要的参数。super必须在子类构造函数中的第一行出现,因为它会初始化基类的属性。
示例:
class Animal { name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { breed: string; constructor(name: string, breed: string) { super(name); // 调用基类构造函数,初始化 name 属性 this.breed = breed; } } const dog = new Dog("Buddy", "Golden Retriever"); console.log(dog.name); // 输出: Buddy console.log(dog.breed); // 输出: Golden Retriever在这个例子中,
Dog类通过super(name)调用基类Animal的构造函数,并传递name参数来初始化继承的name属性。 - 子类的构造函数可以使用
-
super调用基类方法:- 除了在构造函数中使用
super()调用基类构造函数,super还可以用来调用基类的方法。
示例:
class Animal { speak() { console.log("Animal is speaking"); } } class Dog extends Animal { speak() { super.speak(); // 调用基类的 speak 方法 console.log("Dog is barking"); } } const dog = new Dog(); dog.speak(); // 输出: Animal is speaking // 输出: Dog is barking在这个例子中,
Dog类重写了speak方法,但通过super.speak()调用了基类Animal的speak方法。 - 除了在构造函数中使用
-
传递参数给基类构造函数:
- 如果基类的构造函数需要参数,子类在调用
super()时必须传递相应的参数。
示例:
class Vehicle { brand: string; constructor(brand: string) { this.brand = brand; } } class Car extends Vehicle { model: string; constructor(brand: string, model: string) { super(brand); // 调用基类构造函数,传递 brand 参数 this.model = model; } } const car = new Car("Toyota", "Corolla"); console.log(car.brand); // 输出: Toyota console.log(car.model); // 输出: Corolla - 如果基类的构造函数需要参数,子类在调用
总结:
在 TypeScript 中,子类可以通过 super 关键字调用基类的构造函数和方法。super 必须在子类构造函数的第一行使用,用于初始化从基类继承的属性。通过 super,子类不仅能调用基类的构造函数,还能访问和调用基类的方法。