TypeScript 类继承详解

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

TypeScript 中的继承介绍

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

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

假设有下面一个 Person 类:

class Person {
  constructor(private firstName: string, private lastName: string) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  getFullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
  describe(): string {
    return `This is ${this.firstName} ${this.lastName}.`;
  }
}

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

class Employee extends Person {
  //..
}

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

构造函数

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

class Employee extends Person {
  constructor(firstName: string, lastName: string, private jobTitle: string) {
    // call the constructor of the Person class:
    super(firstName, lastName);
    this.jobTitle = jobTitle;
  }
}

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

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

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

let employee = new Employee('John', 'Doe', 'Web Developer');

console.log(employee.getFullName());
console.log(employee.describe());

输出:

John Doe
This is John Doe.

方法重载

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

class Employee extends Person {
  constructor(firstName: string, lastName: string, private jobTitle: string) {
    super(firstName, lastName);
    this.jobTitle = jobTitle;
  }

  describe(): string {
    return super.describe() + `I'm a ${this.jobTitle}.`;
  }
}

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

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

输出:

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

小结

教程来源于Github,感谢cody1991大佬的无私奉献,致敬!

技术教程推荐

如何设计一个秒杀系统 -〔许令波〕

程序员的数学基础课 -〔黄申〕

玩转Spring全家桶 -〔丁雪丰〕

Vue开发实战 -〔唐金州〕

Swift核心技术与实战 -〔张杰〕

NLP实战高手课 -〔王然〕

打造爆款短视频 -〔周维〕

MySQL 必知必会 -〔朱晓峰〕

搞定音频技术 -〔冯建元 〕