首页 > Web开发 > 详细

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

时间:2020-04-04 19:26:43      阅读:63      评论:0      收藏:0      [点我收藏+]
在面向类的语言中,可以先定义一个类,然后定义一个继承前者的类。后者通常被称为 “子类”,前者通常被称为 “父类”。这些术语显然是类比父母和孩子。

 

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

 

思考下面关于类继承的代码 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 个发动机的点火装置

 

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

原文:https://www.cnblogs.com/wzndkj/p/12632945.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!