TypeScript Class

453 阅读2分钟

readonlypublicprotectedprivate 描述符

  class Father {
    public readonly addr: string;  // readonly 只读属性,只读属性必须在声明时或构造函数里被初始化。
    public sex: string;  // 可以在类、派生类以及外部访问
    protected name: string;  // 可以在类 Father 及其派生类中访问
    private age: number;  // 只能在类 Father 中访问
    constructor(name: string, age: number, addr: string, sex: string) {
        this.name = name;
        this.age = age;
        this.addr = addr;
        this.sex = sex;
    }
  }
  
  class child extends Father {
    constructor(name: string, age: number, addr: string, sex: string) {
        super(name, age, addr, sex)
    }
    print() {
        console.log(this.name,this.age)  // 报错 属性“age”为私有属性,只能在类“Father”中访问
    }
  }
  let child = new Child('wang',22,'江西省', 'boy);
  console.log(child.addr);  // '江西省'
  child.addr = '广东省';
  child.sex = 'girl'; // 报错 无法分配到 "sex" ,因为它是只读属性。

构造函数也可以被标记成 protected。 这意味着这个类不能在包含它的类外被实例化,但是能被继承。比如,

  class Person {
      protected name: string;
      protected constructor(theName: string) { this.name = theName; }
  }

  // Employee 能够继承 Person
  class Employee extends Person {
      private department: string;

      constructor(name: string, department: string) {
          super(name);
          this.department = department;
      }

      public getElevatorPitch() {
          return `Hello, my name is ${this.name} and I work in ${this.department}.`;
      }
  }

  let howard = new Employee("Howard", "Sales");
  let john = new Person("John"); // 错误: 'Person' 的构造函数是被保护的.

静态属性、参数属性、存取器

  class Animal {
    static origin = {x: 0, y: 0};  // 静态属性  只能通过 Animal.origin 访问
    constructor(private _name: string) { // 参数属性	
        this._name = name;
    }
    get name(): string {  // 存取器 get 方法
      return this._name;
    }
    set name(name: string): void {  // 存取器 set 方法
     if(/^w/.test(name)) {
     	this._name = name;
     } else {
      	console.log('error');
     }
  }

抽象类

  abstract class Animal {
      abstract makeSound(): void;
      move(): void {
          console.log('roaming the earch...');
      }
  }

抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。 抽象方法的语法与接口方法相似。 两者都是定义方法签名但不包含方法体。 然而,抽象方法必须包含 abstract关键字并且可以包含访问修饰符。

把类当做接口使用

  class Point {
      x: number;
      y: number;
  }

  interface Point3d extends Point {
      z: number;
  }

  let point3d: Point3d = {x: 1, y: 2, z: 3};