TypeScript 类(Classes)
TypeScript 完全支持 ES6 中引入的 class
关键字,并添加了一些额外的特性。让我们逐步了解 TypeScript 中类的概念和用法。
1. 基本类声明
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
let cat = new Animal("Whiskers");
cat.move(10);
这个例子展示了:
- 类的基本结构
- 构造函数的使用
- 方法的定义
2. 继承
TypeScript 支持基于类的程序设计中一个核心原则:继承。
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
move(distanceInMeters = 5) {
console.log("Running...");
super.move(distanceInMeters);
}
}
let dog = new Dog("Rex");
dog.bark();
dog.move(10);
这个例子展示了:
- 如何使用
extends
关键字实现继承 - 如何在子类中重写父类的方法
- 如何使用
super
关键字调用父类的方法
3. 公共,私有与受保护的修饰符
TypeScript 支持面向对象程序设计的常见修饰符:
class Person {
public name: string;
private age: number;
protected hobby: string;
constructor(name: string, age: number, hobby: string) {
this.name = name;
this.age = age;
this.hobby = hobby;
}
}
class Employee extends Person {
private department: string;
constructor(name: string, age: number, hobby: string, department: string) {
super(name, age, hobby);
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
let howard = new Employee("Howard", 42, "Fishing", "Sales");
console.log(howard.getElevatorPitch());
// console.log(howard.age); // 错误:'age' 是私有的
public
修饰的成员可以自由访问。private
修饰的成员只能在声明它的类中访问。protected
修饰的成员可以在声明它的类及其子类中访问。
4. 只读属性
使用 readonly
关键字将属性设置为只读:
class Octopus {
readonly name: string;
readonly numberOfLegs: number = 8;
constructor(theName: string) {
this.name = theName;
}
}
let dad = new Octopus("Man with the 8 strong legs");
// dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.
5. 存取器
TypeScript 支持通过 getters/setters 来截取对对象成员的访问:
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (newName && newName.length > 2) {
this._fullName = newName;
} else {
console.log("Error: Name should be longer than 2 characters");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
6. 静态属性
使用 static
关键字定义静态成员:
class Grid {
static origin = {x: 0, y: 0};
calculateDistanceFromOrigin(point: {x: number; y: number;}) {
let xDist = point.x - Grid.origin.x;
let yDist = point.y - Grid.origin.y;
return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
}
constructor(public scale: number) { }
}
let grid1 = new Grid(1.0);
let grid2 = new Grid(5.0);
console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));
你们学会了么?