TypeScript类

427 阅读2分钟

TypeScript class

class 基本使用

class Person {
  _name: string;
  age: number;

  constructor(p: { _name: string; age: number }) {
    this._name = p._name;
    this.age = p.age;
    console.log(b);
  }

  eating() {
    console.log(this.age, this._name);
  }
}

const xm = new Person({ _name: '小明', age: 24 });
xm.eating();

class 继承

class Person {
  _name: string;
  age: number = 0;

  constructor(_name: string, age?: number) {
    this._name = _name;
    age && (this.age = age);
  }

  eating() {
    console.log('eating');
  }
}

class Student extends Person {
  sno: number = 0;

  constructor(_name: string, age: number, sno?: number) {
    super(_name, age); // 父类的 constructor
    sno && (this.sno = sno);
  }

  eating() {
    // 对父类的方法不满意可以 重写父类方法
    super.eating(); // 调用父类原来方法
    console.log('子类新方法');
  }

  studying() {
    console.log('studying');
  }
}

const xm = new Student('小明', 23);

class 修饰符

  • public 默认就是 public, 开放的

  • private 定义该属性只能的这个类的内部访问 (一般私有属性名字下划线开头)

  • protected 定义该属性只能在 这个类 或者 这个类的子类 中访问

  • readonly 定义该属性只读

    class Person {
      private _name: string = ''; // 定义私有属性 (class 外部不可访问)
      protected protectedKey: string =
        '这个是受保护的属性, 只能在类 | 子类 的内部 访问';
    
      readonly friend?: Person;
    
      constructor(_name: string, friend?: Person) {
        this._name = _name;
        this.friend = friend;
      }
    }
    
    class Student extends Person {
      getProtected() {
        console.log(this.protectedKey);
      }
    }
    
    new Person('ccc', new Person('zn'));
    

class 访问器 get / set

class Person {
  private _name: string = '';

  get name() {
    return this._name;
  }

  set name(newName: string) {
    this._name = newName;
  }
}

new Person().name = 'cqc'; // set

抽象类

特征:

  1. 抽象类不能被实例化
  2. 抽象属性必须要在抽象类里面(抽象方法不需要方法体, 抽象属性不需要值)
  3. 其他类如果继承了这个抽象类, 必须实现该抽象类下的抽象属性, ==除非被继承的类还是一个抽象类==
  • 应用场景 在定义很多==通用==的嗲用接口时候, 通常会让调用者传入父类, 通过堕胎来实现更加灵活的调用方式, 在父类中不需要对某些方法进行具体实现 (在某些公共方法中用来保证传入的参数的正确性)
// 抽象类不能被实例化
abstract class Shape {
  /*
    abstract 表示抽象属性  必须写在抽象类中,
    如果是一个抽象方法, 那么其不需要方法体
  */
  abstract getArea(): number; // 需要自己实现
  name = '我是一个抽象类'; // 正常被继承
}

class Circle extends Shape {
  getArea() {} // 实现 abstract 的 class 中的抽象属性
}

class Rectangle extends Shape{
  getArea() {} // 实现 abstract 的 class 中的抽象属性
}

// 保证传入的属性有需要的方法
function makeArea(shape: Shape) {
  ...
  return shape.getArea();
}