带你正确了解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') 

 

posted @ 2017-06-30 22:05  hi?*  阅读(203)  评论(0编辑  收藏  举报