带你入门 JavaScript ES6 (四)

发布时间:2019-08-09 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了带你入门 JavaScript ES6 (四)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
本文同步带你入门 JavaScript ES6 (四)转载请注明出处。

前面我们学习了:

本章我们将学习 ES6 中的 了解类基本定义和继承相关知识

一、概述

ES6 中的 是基于原型的继承语法糖,本质上它是一个 function 类型

1.1 原型声明

function Car(engines) {
    this.engines = engines
    this.run = false
}

Car.PRototyPE.startEngines = function() {
    console.LOG("running ...")
    this.run = true
}

const yourCar = new Car(1)
yourCar.startEngines()


const myCar = new Car(2)
myCar.startEngines()

1.2 类声明

class Car {
    constructor(engines){
        this.engines = engines
        this.run = false
    }

    startEngines(){
        console.log("running ...")
        this.run = true
    }
}

const yourCar = new Car(1)
yourCar.startEngines()


const myCar = new Car(2)
myCar.startEngines()

console.log(typeof Car)// function

使用类声明是,需要先声明类,然后才能访问,否则抛出ReferenceError。这一点不同于函数声,函数声明提升作用域,而无需事先声明

二、 类声明

2.1 构造方法

使用关键词 constructor 声明的方法,用于在创建和实例化类对象。

2.2 方法

如示例 1.2 中定义的 startEngines 方法

2.3 静态方法

使用关键字 static 修饰的方法,允许通过类名直接调用静态方法而无需实例化。

class Car {
    constructor(engines = 1) {
        this.engines = engines
        this.run = false
    }

    static startEngines() {        
        console.log("running ...")
        this.run = true
    }
}

Car.startEngines()

三、类的继承

extends 关键词用于创建基于另一个类的子类定义
当子类存在构造函数时, 需要在使用 this 之前调用 super()

class Animal {
    constructor (name) {
        this.name = name
    }
}

class Dog extends Animal {
    constructor (name) {
        super(name)
        this.legs = 4;
    }

    run() {
        console.log('running ...')
    }
}

const lily = new Dog('lily')

lily.run();

console.log( lily instanceof Dog)// trye
console.log( lily instanceof Animal)// true

四、为什么使用类

  • 简化代码
  • 相比原型继承代码解构更清晰
  • 所有类方法在声明类时声明

五、注意的点

  • 实例化类,使用 new 关键词
  • 类方法之间无需使用逗号
  • 子类构造函数使用 super() 函数完成父类构造@R_360_2469@

参考

MDN 类

脚本宝典总结

以上是脚本宝典为你收集整理的带你入门 JavaScript ES6 (四)全部内容,希望文章能够帮你解决带你入门 JavaScript ES6 (四)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。