Visual LabINTERACTIVE LEARNING
JavaScript 内核第 2 / 5 章

类与面向对象能力

整理继承、多态、封装、抽象类和成员修饰符。

TypeScript泛型类型体操
进阶预计 48 分钟查看源文 ↗

Class

类的继承

提示

子类可以继承父类中的属性和方法,减少相同代码的重复编写 js/ts中是单继承,只能继承单一父类

类的多态:

父类引用指向子类对象

//亦即父类作为子类的实例的类型,这样可以提前确定好子类实例中拥有哪些方法,
//让中间层可以调用,中间层不再关注具体的实现,只需要调用对应的方法即可
const square: Shape = new Square(10);  //见抽象类中的具体实现

类的封装

提示

紧凑的组织代码,

类成员修饰符

  • 成员修饰符

    • public 公开访问 default
    • private 私有属性 子类和实例不能访问
    • protected 保护属性 子类可以访问( 使用),子类实例不能访问
    • readonly 只能在声明时或构造函数里被初始化,其他地方不能修改
    • static 静态属性,类可以访问,实例不能访问

提示

当构造函数修饰为 protected 时,该类只允许被继承: 当构造函数修饰为 private 时,该类不允许被继承或者实例化

抽象类

❤️ 提示

抽象类不能被实例化,只能被继承 抽象类中的抽象方法必须被子类实现 抽象类中的抽象方法可以没有具体实现,也可以有具体实现

// 抽象类
abstract class Shape {
  abstract getAera(): number;
}

class Circle extends Shape {
  private r: number;
  constructor(radius: number) {
    super();
    this.r = radius;
  }
  getAera() {
    return Math.PI * this.r ** 2;
  }
}

class Square extends Shape {
  private a: number;
  constructor(a: number) {
    super();
    this.a = a;
  }
  getAera() {
    return this.a ** 2;
  }
}

function makeAera(a: Shape) {
  return a.getAera();
}

const circle = new Circle(10);
const square: Shape = new Square(10);
console.log(makeAera(circle));
console.log(makeAera(square));

类的访问器 getter /setter

❤️ 提示

访问器是一种特殊的方法,用来读取或设置某个属性的值 访问器不会被编译到 js 中,只会在编译阶段进行类型检查 访问器不必须有 get 和 set 方法,可以只有 get 方法,也可以只有 set 方法,一般用于拦截私有属性的操作 只实现get 方法,那么该属性为 readonly 访问器的参数不能有修饰符,也不能有默认值

参数属性(TS语法糖)

提示

在constructor方法中,参数前面加上修饰符,即可简化属性的编写

class Person {

  constructor(public name: string, public age: number) {

  }
}

const p1 = new Person('Max', 30);
console.log(p1.name);

类的类型特性

提示

  • 类可以创建实例
  • 类可以作为实例的类型
  • 类可以作为有构造签名的函数- 工厂函数中使用