你不知道的JS系列上( 43 ) - JS 类的继承

在面向类的语言中,可以先定义一个类,然后定义一个继承前者的类。后者通常被称为 “子类”,前者通常被称为 “父类”。这些术语显然是类比父母和孩子。

 

定义好一个子类之后,相对于父类来说它就是一个独立并且完全不同的类。子类包含父类行为的原始副本,但是也可以重写所有继承的行为甚至定义新行为

 

思考下面关于类继承的代码 Vehicle 和 Car
class Vehicle {
  constructor() {
    this.engines = 1
  }  

  ignition () {
    console.log('Turning on my engine');
  }

  drive () {
    this.ignition();
    console.log('Steering and moving forward!')
  }
}

class Car extends Vehicle {
  constructor() {
    super()
    this.wheels = 4
  }

  drive () {
    this.ignition()
    console.log('Rolling on all ', this.wheels, ' wheels')
  }
}

class SpeedBoat extends Vehicle {
  constructor() {
    super();
    this.engines = 2
  }

  ignition () {
    console.log('Turning on my ', this.engines, ' engines.');
  }

  pilot() {
    this.ignition();
    console.log('Speeding through the water with ease!')
  }
}

我们通过定义 Vehicle 类来假设一种发动机,一种点火方式,一种驾驶方式。这个类是一个抽象的概念。接下来定义了两类具体的交通工具:Car 和 SpeedBoat。它们都从 Vehicle 继承了通用的特性并根据自身类别修改了某种特性。汽车需要 4 个轮子,快艇需要 2 个发动机,因此它必须启动 2 个发动机的点火装置

 

posted @ 2020-04-04 17:57  wzndkj  阅读(128)  评论(0编辑  收藏  举报