• 带你正确了解ES6


    ES6全名是ECMAScript 6,是JavaScript语言的下一代标准。

    Babel,可以将ES6代码转为ES5代码,是一个环境执行

    ES6最常用的特性:let, const, class, extends, super, arrow functions, template string, destructuring, default, rest arguments

    let, const类似于var,是ES6的新的声明方式。

    原型、构造函数,继承看起来更清晰。

     1 class Animal {
     2     constructor(){
     3         this.type = 'animal'
     4     }
     5     says(say){
     6         console.log(this.type + ' says ' + say)
     7     }
     8 }
     9 
    10 let animal = new Animal()
    11 animal.says('hello') //animal says hello
    12 
    13 class Cat extends Animal {
    14     constructor(){
    15         super()
    16         this.type = 'cat'
    17     }
    18 }
    19 
    20 let cat = new Cat()
    21 cat.says('hello') //cat says hello

     首先用class定义了一个“类”,可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。简单地说,constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实例对象可以共享的,Class之间可以通过extends关键字实现继承,super关键字,它指代父类的实例(即父类的this对象),子类必须在constructor方法中调用super方法,否则新建实例时会报错。

    箭头式函数最突出ES6新特性。

    1 function(x, y) { 
    2     x++;
    3     y--;
    4     return x + y;
    5 }
    6 (x, y) => {x++; y--; return x+y}

    比如在一些没有传参的函数里,需要设默认值。

    function animal(type){
        type = type || 'cat'  
        console.log(type)
    }
    animal()

    ES6可以这么写
    function animal(type = 'cat'){
        console.log(type)
    }
    animal()

    还有一种写法,如传入多个参数

    function animals(...types){
        console.log(types)
    }
    animals('cat', 'dog', 'fish') 
  • 相关阅读:
    node.js(八 --- express)
    node.js(六 --- 文件系统模块fs)
    node.js( 五 --- 常用工具util)
    node.js(四 --- 全局对象)
    python 判断变量是否存在 防止报错
    python requests 的cookie 操作
    DDOS 攻击的防范
    python图片识别
    php常见问题-foreach和引用造成的问题。
    数据库数据类型选择
  • 原文地址:https://www.cnblogs.com/chw8/p/7100836.html
Copyright © 2020-2023  润新知