1. 类的定义

  1. class City {
  2. // 成员变量,定义在类中,如果没有在构造函数中初始化则需要在此处赋初始值
  3. cname: string;
  4. clevel: number;
  5. // 构造函数:初始化
  6. constructor(cName: string, cLevel: number) {
  7. this.cname = cName;
  8. this.clevel = cLevel;
  9. }
  10. // 成员方法:直接定义在类中,会被写入原型中
  11. about() {
  12. console.log('about');
  13. }
  14. }
  15. let c1 = new City('P城', 1);

2. 类的继承

  1. // 同 ES6
  2. class CityChild extends City {
  3. constructor(cName: string, cLevel: number) {
  4. super(cName, cLevel)
  5. }
  6. }

3. 类修饰符

  • public :公有,在类里面、子类、类外部都可以访问
  • protected :保护类型,在类里面、子类可以访问,在类外部无法访问
  • private :私有类型,在类里面可以访问,子类和类外部无法访问。 ```typescript // 父类,即类内部 class Father { // 类内部、子类、类外部可使用 public say() { console.log(‘say’) } // 类内部、子类可使用,类外部不可使用 protected money() { console.log(‘money’) } // 仅类内部使用 private wife() { console.log(‘my wife’) } useMethod() { this.say(); this.money(); this.wife(); } } // 子类 class Son extends Father { useMethod() { this.say(); this.money(); } } // 类外部 const father = new Father(); father.say();
  1. <a name="vcf4B"></a>
  2. # 4. 静态属性和静态方法
  3. 类中设置了 `static` 关键字的属性或方法,只能通过类去调用,不能通过类的实例调用。
  4. > ES6 的语法
  5. ```javascript
  6. class Father {
  7. static run() {
  8. console.log('run')
  9. }
  10. }
  11. // 正确
  12. Father.run();
  13. // 错误
  14. const father = new Father();
  15. father.run();

5. 访问器

gettersetter 可以用来实现数据的封装和有效性检查,防止出现异常数据

ES6 的语法

  1. let passcode = "Hello TypeScript";
  2. class Employee {
  3. private _fullName: string;
  4. get fullName(): string {
  5. return this._fullName;
  6. }
  7. set fullName(newName: string) {
  8. if (passcode && passcode == "Hello TypeScript") {
  9. this._fullName = newName;
  10. } else {
  11. console.log("Error: Unauthorized update of employee!");
  12. }
  13. }
  14. }
  15. let employee = new Employee();
  16. employee.fullName = "Semlinker";
  17. if (employee.fullName) {
  18. console.log(employee.fullName);
  19. }

6. 抽象类

abstract 关键字定义抽象类、抽象方法和属性,抽象类中的抽象方法和属性不包含具体实现。

继承自抽象类的类,叫做派生类。 派生类必须实现抽象类的方法和属性

  1. abstract class Animal {
  2. abstract name: string;
  3. abstract eat(): void;
  4. }
  5. class Dog extends Animal {
  6. name = "dog";
  7. // 必须实现抽象类的抽象方法
  8. eat() { }
  9. }