TypeScript 是一种由微软开发的 JavaScript 的超集,它拓展了 JavaScript 的语法和语义,使得我们在编写大型 JavaScript 应用程序时能够获得更好的可读性、可维护性和可重用性。TypeScript 具备强类型、接口、泛型等特性,让 JavaScript 的开发变得更加严谨和高效。
在 TypeScript 中,我们可以使用类来组织代码并实现面向对象编程的概念,包括类的继承、多态、抽象类等。本文将重点讲述如何在 TypeScript 中建立类的继承和构造函数。
类的继承
类的继承是面向对象编程的核心概念之一,它是通过一个类来派生出另一个类并继承其属性和方法,让代码更加可复用和可扩展。在 TypeScript 中,我们可以使用关键字 extends 来实现类的继承。
下面的示例演示了如何在 TypeScript 中建立一个 Person 类,并从它派生出一个 Employee 类:
// www.javascriptcn.com code example
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}, and I'm ${this.age} years old`);
}
}
class Employee extends Person {
position: string;
salary: number;
constructor(name: string, age: number, position: string, salary: number) {
super(name, age);
this.position = position;
this.salary = salary;
}
work() {
console.log(`I'm working as a ${this.position} and earn ${this.salary} dollars per month`);
}
}
const john = new Employee('John Doe', 30, 'Software Engineer', 5000);
john.greet();
john.work();在上面的示例中,我们定义了一个 Person 类,它包含了两个属性 name 和 age,以及一个方法 greet()。同时,我们派生出了一个 Employee 类,并在其构造函数中使用 super() 调用了父类的构造函数来初始化基类的属性。这样,我们就可以在 Employee 类中访问 Person 类中的属性和方法,并在其基础上进一步扩展出新的属性和方法。
接下来,我们创建了一个 Employee 类的实例 john,并分别调用了它的 greet() 和 work() 方法。由于 Employee 类继承了 Person 类的所有属性和方法,因此它可以访问基类中的所有属性和方法,并在其基础上进一步扩展功能。
构造函数
构造函数是类的一个特殊方法,它在创建类的实例时被调用,并用于初始化实例的属性。在 TypeScript 中,我们可以使用 constructor 关键字来定义一个类的构造函数。
下面的示例演示了如何在 TypeScript 中建立一个具有构造函数的类:
// www.javascriptcn.com code example
class Car {
make: string;
model: string;
year: number;
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
getInfo() {
console.log(`This car is made by ${this.make}, model ${this.model}, year ${this.year}`);
}
}
const ferrari = new Car('Ferrari', '458 Italia', 2015);
ferrari.getInfo();在上面的示例中,我们定义了一个名为 Car 的类,它包含了三个属性 make、model 和 year,以及一个方法 getInfo()。同时,我们在其构造函数中使用传入的参数初始化了实例的属性。
接下来,我们创建了一个 Car 类的实例 ferrari,并调用了它的 getInfo() 方法来展示其属性值。由于我们在构造函数中对实例的属性进行了初始化,因此它们已经具备了初始值,并可以在类的实例方法中被访问和使用。
结语
本文介绍了 TypeScript 中如何建立类的继承和构造函数,这些是面向对象编程的两个核心概念,也是 TypeScript 中使用得比较多的特性。通过本文的学习,相信读者可以掌握 TypeScript 类的基础语法和用法,进一步提高自己的编程技能和水平。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/6792ef4e504e4ea9bd6e8a3a