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 个发动机的点火装置

  • 相关阅读:
    C++ 函数设计原则
    C++ 转换函数搭配友元函数
    C++ 自动转换和强制类型转换(用户自定义类类型)
    C++ rand函数
    C++ 状态成员
    C++ 友元函数
    C++ 运算符重载
    RabbitMQ的简单应用
    Python的正则表达式
    Python的应用小案例
  • 原文地址:https://www.cnblogs.com/wzndkj/p/12632945.html
Copyright © 2011-2022 走看看