TypeScript 类
在面向对象编程(OOP)中,类是一种用于创建对象的蓝图或模板。它封装了数据和操作数据的方法。TypeScript 作为 JavaScript 的超集,也支持使用类来组织代码。
类的定义
在 TypeScript 中,使用class关键字来定义一个类。类通常包含以下几个部分:
构造函数(Constructor): 用于初始化类的实例,使用constructor关键字定义。
属性(Properties): 类的数据成员,用于存储对象的状态。
方法(Methods): 类的函数成员,用于操作类的数据。
下面是一个简单的类定义示例
class Person {
  private name: string;
  private age: number;
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
  public sayHello() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
}
在这个例子中,我们定义了一个Person类,它有两个私有属性name和age,以及一个构造函数和一个公共方法sayHello。
访问修饰符
TypeScript 提供了三种访问修饰符来控制类成员的可见性:
public: 默认修饰符,表示成员可以在任何地方被访问。
private: 表示成员只能在类的内部访问。
protected: 表示成员可以在类的内部以及子类中访问。
除了访问修饰符,TypeScript 还提供了readonly修饰符,用于指定属性只能在构造函数中初始化,之后不能被修改。
class Circle {
  readonly radius: number;
  constructor(radius: number) {
    this.radius = radius;
  }
}
继承
TypeScript 支持使用extends关键字实现类的继承。子类可以继承父类的属性和方法,并且可以添加自己的属性和方法或覆盖父类的方法。
class Animal {
  protected name: string;
  constructor(name: string) {
    this.name = name;
  }
  move(distance: number = 0) {
    console.log(`${this.name} moved ${distance}m.`);
  }
}
class Dog extends Animal {
  bark() {
    console.log('Woof! Woof!');
  }
  move(distance = 5) {
    console.log('Running...');
    super.move(distance);
  }
}
在这个例子中,Dog类继承了Animal类,并添加了自己的bark方法。它还覆盖了父类的move方法,在调用父类方法前添加了自己的逻辑。
除了使用extends实现继承,TypeScript 还支持使用implements关键字实现接口。一个类可以实现多个接口,用逗号分隔。
interface Printable {
  print(): void;
}
class Report implements Printable {
  print() {
    console.log('Printing report...');
  }
}