fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

[TypeScript] 第1536天 在TypeScript中如何从子类调用基类构造函数?

Open haizhilin2013 opened this issue 2 years ago • 1 comments
trafficstars

第1536天 在TypeScript中如何从子类调用基类构造函数?

3+1官网

我也要出题

haizhilin2013 avatar Jun 29 '23 20:06 haizhilin2013

在 TypeScript 中,当你创建一个类的子类时,可以通过使用 super 关键字来调用基类的构造函数。调用基类的构造函数是必需的,尤其是在基类有参数化构造函数的情况下。以下是一些示例和详细解释:

基本示例

假设你有一个基类 Animal 和一个子类 Dog

class Animal {
    name: string;

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

    makeSound() {
        console.log(`${this.name} makes a sound`);
    }
}

class Dog extends Animal {
    breed: string;

    constructor(name: string, breed: string) {
        super(name); // 调用基类的构造函数
        this.breed = breed;
    }

    makeSound() {
        console.log(`${this.name} barks`);
    }
}

const myDog = new Dog('Rex', 'German Shepherd');
myDog.makeSound(); // 输出: Rex barks

在这个示例中:

  • Animal 类有一个构造函数,它接受一个参数 name
  • Dog 类继承自 Animal,它的构造函数接受两个参数:namebreed
  • Dog 的构造函数使用 super(name) 调用了基类 Animal 的构造函数,以便设置 name 属性。
  • 子类 Dog 的构造函数中调用 super(name) 是必需的,这样基类 Animal 的构造函数才能正确初始化 name 属性。

需要注意的事项

  1. super 调用位置

    • 在 TypeScript 中,必须在子类构造函数中使用 super 调用基类构造函数,并且必须在使用 this 之前调用 super
  2. 初始化顺序

    • super 必须先于 this 进行调用。这是因为在调用基类的构造函数之前,子类的 this 不能被引用。
  3. 无参数构造函数

    • 如果基类没有参数化的构造函数,子类的构造函数也必须调用 super(),即使没有传递参数。

另一个示例

class Vehicle {
    wheels: number;

    constructor(wheels: number) {
        this.wheels = wheels;
    }
}

class Car extends Vehicle {
    brand: string;

    constructor(wheels: number, brand: string) {
        super(wheels); // 调用基类的构造函数
        this.brand = brand;
    }

    displayInfo() {
        console.log(`This car is a ${this.brand} with ${this.wheels} wheels.`);
    }
}

const myCar = new Car(4, 'Toyota');
myCar.displayInfo(); // 输出: This car is a Toyota with 4 wheels.

在这个示例中,Vehicle 类有一个接受 wheels 参数的构造函数,而 Car 类继承自 Vehicle,并且它的构造函数需要调用 super(wheels) 来初始化 wheels 属性。

llccing avatar Jun 28 '24 05:06 llccing