title: 类继承

类继承

原文地址

在本教程中,你将了解 TypeScript 中继承的概念,以及如何使用它来复用其他类的功能。

TypeScript 中的继承介绍

可以让其他的类复用它的属性和方法,这在 TypeScript 中被称为继承。继承其他类的属性和方法的类被称为子类,被继承的类被称为父类,这些名字来自自然中孩子继承父母基因的说法。继承让你可以复用现有类的功能,而不需要重写一遍。

JavaScript 使用 原型继承 的方式实现类,而非 JavaC# 语言的类继承方式。 ES6 引入的 语法是 JavaScript 原型继承的语法糖,TypeScript 也支持这种语法。

假设有下面一个 Person 类:

  1. class Person {
  2. constructor(private firstName: string, private lastName: string) {
  3. this.firstName = firstName;
  4. this.lastName = lastName;
  5. }
  6. getFullName(): string {
  7. return `${this.firstName} ${this.lastName}`;
  8. }
  9. describe(): string {
  10. return `This is ${this.firstName} ${this.lastName}.`;
  11. }
  12. }

使用 extends 关键字继承其它类,比如下面的 Employee 类继承了 Person 类:

  1. class Employee extends Person {
  2. //..
  3. }

在这个例子中,Employee 是子类,而 Person是父类。

构造函数

因为 Person 类中有一个初始化 firstNamelastName 属性的构造函数,你需要在 Employee 类的构造函数中调用父类的构造函数来初始化这些属性。要在子类的构造函数中调用父类的构造函数,可以使用 super() 语法:

  1. class Employee extends Person {
  2. constructor(firstName: string, lastName: string, private jobTitle: string) {
  3. // call the constructor of the Person class:
  4. super(firstName, lastName);
  5. this.jobTitle = jobTitle;
  6. }
  7. }

下面创建了一个 Employee 类的实例:

  1. let employee = new Employee('John', 'Doe', 'Front-end Developer');

因为 Employee 类继承了 Person 类的方法和属性,你可以在 employee 对象上调用 getFullName()describe() 方法,如下所示:

  1. let employee = new Employee('John', 'Doe', 'Web Developer');
  2. console.log(employee.getFullName());
  3. console.log(employee.describe());

输出:

  1. John Doe
  2. This is John Doe.

方法重载

当你调用 employee 对象上的 employee.describe() 方法的时候,Person 类的 describe() 方法会被执行,显示 This is John Doe 信息。如果 Employee 类想要有属于自己的 describe() 方法,可以在 Employee 类中定义 describe() 方法,如下所示:

  1. class Employee extends Person {
  2. constructor(firstName: string, lastName: string, private jobTitle: string) {
  3. super(firstName, lastName);
  4. this.jobTitle = jobTitle;
  5. }
  6. describe(): string {
  7. return super.describe() + `I'm a ${this.jobTitle}.`;
  8. }
  9. }

describe() 方法中,我们使用 super.methodInParentClass() 的语法调用父类的 describe() 方法。如果你在 employee 对象上调用 describe() 方法,Employee 类的 describe() 方法会被调用:

  1. let employee = new Employee('John', 'Doe', 'Web Developer');
  2. console.log(employee.describe());

输出:

  1. This is John Doe.I'm a Web Developer.

小结

  • 使用 extends 关键字允许一个类继承另外一个类;
  • 在子类的构造函数中使用 super 方法调用父类的构造函数,在子类的方法中使用 super.methodInParentClass() 语法调用父类的 methodInParentClass() 方法。