了解ES6

ES6即ES2015,使用Babel可将ES6代码转换为ES5代码。最常用的ES6语法有let,const,class,extends,super,arrow functions,template string,destructuring,default,rest arguments。

let,const

var name = 'mengl';
if(1){
    var name = 'obama';
    console.log(name);//obama    
}
console.log(name);//obama
var name = 'mengl';
if(1){
    let name = 'obama';
    console.log(name);//obama    
}
console.log(name);//mengl

  let只在代码块内有效,var会将记数的循环变量暴露为全局变量,变量提升等问题,而let不会。

var arr = [];
for(var i=0;i<10;i++){
  arr[i] = function(){
    console.log(i);   
  }
}
arr[0]();//10
var arr = [];
for(let i=0;i<10;i++){
  arr[i] = function(){
    console.log(i);
  }
}
arr[0]();//0

  const和let,var一样也是用来声明变量,const声明的变量不能修改,const的一个很好的应用场景就是引用第三方库时声明的变量,如const monent = require('moment');

const PI = Math.PI;
PI = 3;//报错

class,extends,super

class Animal{
  constructor(){
    this.type = 'animal';
  }//后面不能加逗号   says(say){     console.log(this.type + ' says ' + say);   }
} let animal = new Animal(); animal.says('hello');//animal says hello class Cat extends Animal{   constructor(){     super();//返回父类的this对象     this.type = 'cat';   } } let cat = new Cat(); cat.says('hello');//cat says hello

  ES6中可以用更简洁的方式编写对象字面量中的方法,如constructor和says。通过new命令生成对象时默认调用constructor方法,若未显式定义,则自动添加constructor方法,constructor方法默认返回实例对象this,但是也可以指定constructor方法返回一个全新的对象让返回的对象不是该类的实例。ES6明确定义,class内只有静态方法,没有静态属性。

arrow function

  比ES5 function写法方便简洁很多,如

function add(x,y){
  return x + y;
}
let add = (x,y) => x + y

  多条语句时,箭头右边加{},function无参数或多参数时,箭头左边加括号,返回值为对象时,箭头右边加括号。

  箭头函数无自己的this,无法当做构造函数使用,所以call和apply,bind也无法改变this指向,this继承于外层。

window.color = "red";
let color = "green";
let obj = {
  color: "blue"
};
let sayColor = () => {
  return this.color;
};
sayColor.apply(obj);//red

template string

  用反引号`标志起始,用${}引用变量,如

$("#result").append(`
  There are <b>${basket.count}</b> items
  in your basket, <em>${basket.onSale}</em>
  are on sale!
`);

destructuring 解构

  按照一定模式,从数组/对象中提取值,对变量进行赋值,称为解构。

  ES5

var cat = 'ken'
var dog = 'lili'
var zoo = {cat: cat, dog: dog}
console.log(zoo)  //Object {cat: "ken", dog: "lili"}

  ES6

let cat = 'ken'
let dog = 'lili'
let zoo = {cat, dog}
console.log(zoo)  //Object {cat: "ken", dog: "lili"}

  

let dog = {type: 'animal', many: 2}
let { type, many} = dog
console.log(type, many)   //animal 2

  default

意思就是默认值

function fn(type){
  type = type || 'cat';//传统做法
console.log(type);
}
function fn(type = 'cat'){
  console.log(type);
}

  rest

function animals(...types){
    console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]
//ES5使用arguments

 

参考资料:

http://www.jianshu.com/p/ebfeb687eb70

http://www.infoq.com/cn/articles/es6-in-depth-arrow-functions

http://www.cnblogs.com/huansky/p/5684867.html

posted @ 2017-04-18 14:40  梦泪  阅读(360)  评论(0)    收藏  举报