TypeScript 继承
摘要:在本教程中,你将了解 TypeScript 继承概念以及如何使用它来重用另一个类的功能。
TypeScript继承简介
一个类可以重用另一个类的属性和方法。 这在 TypeScript 中称为继承。
继承属性和方法的类称为子类。 属性和方法被继承的类称为父类。 这些名字来源于孩子从父母那里继承基因的本质。
继承允许你重用现有类的功能而无需重写它。
JavaScript 使用原型继承,而不是像 Java 或 C# 那样的经典继承。 ES6 引入了类语法,它只是原型继承的语法糖。 TypeScript 像 ES6 一样支持继承。
假设你有以下 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 类有一个构造函数来初始化 firstName 和 lastName 属性,所以你需要在 Employee 类的构造函数中通过调用其父类的构造函数来初始化这些属性。
要在子类的构造函数中调用父类的构造函数,可以使用 super() 语法。 例如:
class Employee extends Person {
constructor(
firstName: string,
lastName: string,
private jobTitle: string) {
// call the constructor of the Person class:
super(firstName, lastName);
}
}
下面创建了 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 类中定义它,如下所示:
class Employee extends Person {
constructor(
firstName: string,
lastName: string,
private jobTitle: string) {
super(firstName, lastName);
}
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.
概括
- 使用
extends关键字允许一个类继承另一个类。 - 在子类的构造函数中使用
super()来调用父类的构造函数。 另外,使用super.methodInParentClass()语法可以在子类方法中调用methodInParentClass()。