# 类
在本教程中,你将学习 TypeScript 中的类。
# TypeScript 中的类介绍
JavaScript 不像其他编程语言,如 Java 和 C# ,有类的概念,在 ES5 中,你可以通过构造函数和 原型继承 (opens new window) 来创建一个“类”。比如要创建一个有 ssn,firstName 和 lastName 三个属性的 Person 类,你可以使用如下所示的构造函数:
function Person(ssn, firstName, lastName) {
  this.ssn = ssn;
  this.firstName = firstName;
  this.lastName = lastName;
}
1
2
3
4
5
2
3
4
5
接下来,定义一个原型方法,通过连接 firstName 和 lastName 属性值的方式来获得人名全称:
Person.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`;
};
1
2
3
2
3
然后可以通过 Person “类”创建一个新的对象:
let person = new Person('171-28-0926', 'John', 'Doe');
console.log(person.getFullName());
1
2
2
它会在控制台上打印出下面的信息:
John Doe
1
ES6 允许你定义一个类 (opens new window),它是创建对应的构造函数和原型继承的语法糖:
class Person {
  ssn;
  firstName;
  lastName;
  constructor(ssn, firstName, lastName) {
    this.ssn = ssn;
    this.firstName = firstName;
    this.lastName = lastName;
  }
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
在上面类的语法中,构造函数已经被明确定义在类中。接下来增加 getFullName() 方法:
class Person {
  ssn;
  firstName;
  lastName;
  constructor(ssn, firstName, lastName) {
    this.ssn = ssn;
    this.firstName = firstName;
    this.lastName = lastName;
  }
  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
使用 Person 类和使用 Person 构造函数创建的对象是一样的:
let person = new Person('171-28-0926', 'John', 'Doe');
console.log(person.getFullName());
1
2
2
TypeScript 中的类给它的属性和方法增加了 类型注释。下面演示了 TypeScript 中的 Person 类的使用方法:
class Person {
  ssn: string;
  firstName: string;
  lastName: string;
  constructor(ssn: string, firstName: string, lastName: string) {
    this.ssn = ssn;
    this.firstName = firstName;
    this.lastName = lastName;
  }
  getFullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
当你给类的属性,构造函数和方法增加类型注释,TypeScript 编译器会进行对应的类型检查。例如,你不能把 ssn 初始化为一个 number 类型的值,下面的代码会抛出错误提示:
let person = new Person(171280926, 'John', 'Doe');
1
# 小结
- 在 TypeScript 中使用 class关键字定义类;
- TypeScript 给 ES6 类的语法添加类型注释,让类的使用更具有健壮性。