zoukankan      html  css  js  c++  java
  • 你不知道的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 个发动机的点火装置

  • 相关阅读:
    xcode 各种项目设置
    poj 2240 floyd算法
    MySQL參数binlog-do-db对binlogs写入的影响
    cocos2D(一)----第一个cocos2D程序
    mahout測试朴素贝叶斯分类样例
    sql for xml query sample
    辛星解读之php中的重点函数第一节之数组函数
    java集合经常出现空指针问题的解决方案
    java常量设置的方式
    java中如果需要精确的计算答案,请避免使用double类型与float类型
  • 原文地址:https://www.cnblogs.com/wzndkj/p/12632945.html
Copyright © 2011-2022 走看看