- Parameters(参数) in ES6
- Template Literals (模板文本)in ES6
- Multi-line Strings (多行字符串)in ES6
- Destructuring Assignment (解构赋值)in ES6
- Enhanced Object Literals (增强的对象文本)in ES6
- Arrow Functions (箭头函数)in ES6
- Promises in ES6
- Block-Scoped Constructs Let and Const(块作用域构造Let and Const)
- Classes(类) in ES6
- Modules(模块) in ES6
- for of 值遍历 in ES6
下面就每点介绍下
Parameters(参数):
默认参数:
function sayHello(name){ //传统的指定默认参数的方式 var name=name||'dude'; console.log('Hello '+name); } //运用ES6的默认参数 function sayHello2(name='dude'){ console.log(`Hello ${name}`); } sayHello();//输出:Hello dude sayHello('Wayou');//输出:Hello Wayou sayHello2();//输出:Hello dude sayHello2('Wayou');//输出:Hello Wayou
不定参数:
//将所有参数相加的函数 function add(...x){ return x.reduce((m,n)=>m+n); } //传递任意个数的参数 console.log(add(1,2,3));//输出:6 console.log(add(1,2,3,4,5));//输出:15
拓展参数:
var people=['Wayou','John','Sherlock']; //sayHello函数本来接收三个单独的参数人妖,人二和人三 function sayHello(people1,people2,people3){ console.log(`Hello ${people1},${people2},${people3}`); } //但是我们将一个数组以拓展参数的形式传递,它能很好地映射到每个单独的参数 sayHello(...people);//输出:Hello Wayou,John,Sherlock //而在以前,如果需要传递数组当参数,我们需要使用函数的apply方法 sayHello.apply(null,people);//输出:Hello Wayou,John,Sherlock
Template Literals (模板文本)
//es5,我们组合一个字符串像这样 var name = 'Your name is ' + first + ' ' + last + '.'; var url = 'http://localhost:3000/api/messages/' + id; //es6,我们可以使用新的语法$ {NAME},并把它放在反引号里 var name = `Your name is ${first} ${last}. `; var url = `http://localhost:3000/api/messages/${id}`;
Multi-line Strings (多行字符串)
//es5中,多行字符串我们一般这样表示 var roadPoem = 'Then took the other, as just as fair,nt' + 'And having perhaps the better claimnt' + 'Because it was grassy and wanted wear,nt' + 'Though as for that the passing therent' + 'Had worn them really about the same,nt'; //es6中,我们用反引号就可以了 var roadPoem = `Then took the other, as just as fair, And having perhaps the better claim Because it was grassy and wanted wear, Though as for that the passing there Had worn them really about the same,`;
Destructuring Assignment (解构赋值)
var [x,y]=getVal(),//函数返回值的解构 {house , mouse} = $('body').data(), // data有house和mouse两个属性数据 [name,,age]=['wayou','male','secrect'];//数组解构 function getVal() { return [ 1, 2 ]; } console.log('x:'+x+', y:'+y);//输出:x:1, y:2 console.log('house:'+house+', mouse:'+mouse);//输出:house:111, mouse:22 console.log('name:'+name+', age:'+age);//输出: name:wayou, age:secrect
Enhanced Object Literals (增强的对象文本)
对象字面量被增强了,写法更加简洁与灵活,同时在定义对象的时候能够做的事情更多了。具体表现在:
- 可以在对象字面量里面定义原型
- 定义方法可以不用function关键字
- 直接调用父类方法
这样一来,对象字面量与前面提到的类概念更加吻合,在编写面向对象的JavaScript时更加轻松方便了。
//通过对象字面量创建对象 var human = { breathe() { console.log('breathing...'); } }; var worker = { __proto__: human, //设置此对象的原型为human,相当于继承human company: 'freelancer', work() { console.log('working...'); } }; human.breathe();//输出 ‘breathing...’ //调用继承来的breathe方法 worker.breathe();//输出 ‘breathing...’
Arrow Functions (箭头函数)
CoffeeScript 就是因为它丰富的箭头函数让很多开发者喜爱。在ES6中,也有了丰富的箭头函数。这些丰富的箭头是令人惊讶的因为它们将使许多操作变成现实,比如,
以前我们使用闭包,this总是预期之外地产生改变,而箭头函数的迷人之处在于,现在你的this可以按照你的预期使用了,身处箭头函数里面,this还是原来的this。
有了箭头函数在ES6中, 我们就不必用that = this或 self = this 或 _this = this 或.bind(this)。例如:
//es5代码 var _this = this; $('.btn').click(function(event){ _this.sendData(); }) //es6中,我们不需要 _this = this $('.btn').click((event) =>{ this.sendData(); })
在箭头函数中,对于单个参数,括号()是可选的,但当你超过一个参数的时候你就需要他们。
//es5 var ids = ['5632953c4e345e145fdf2df8', '563295464e345e145fdf2df9']; var messages = ids.map(function (value, index, list) { return 'ID of ' + index + ' element is ' + value + ' '; // 声明返回 }); //es6 var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']; var messages = ids.map((value, index, list) => `ID of ${index} element is ${value} `); // 隐式返回
Promises
看下面例子:
//es5 setTimeout(function(){ console.log('Yay!'); }, 1000); //es6 var wait1000 = new Promise(function(resolve, reject) { setTimeout(resolve, 1000); }).then(function() { console.log('Yay!'); });
到目前为止,代码的行数从三行增加到五行,并没有任何明显的好处。确实,如果我们有更多的嵌套逻辑在setTimeout()回调函数中,我们将发现更多好处:
//es5 setTimeout(function(){ console.log('Yay!'); setTimeout(function(){ console.log('Wheeyee!'); }, 1000) }, 1000); //es6 var wait1000 = ()=> new Promise((resolve, reject)=> {setTimeout(resolve, 1000)}); wait1000() .then(function() { console.log('Yay!') return wait1000() }) .then(function() { console.log('Wheeyee!') });
Block-Scoped Constructs Let and Const(块作用域构造Let and Const)
//var function calculateTotalAmount (vip) { var amount = 0; if (vip) { var amount = 1; } { // more crazy blocks! var amount = 100; { var amount = 1000; } } return amount; } console.log(calculateTotalAmount(true)); //结果是1000 //let function calculateTotalAmount (vip) { var amount = 0; // probably should also be let, but you can mix var and let if (vip) { let amount = 1; // first amount is still 0 } { // more crazy blocks! let amount = 100; // first amount is still 0 { let amount = 1000; // first amount is still 0 } } return amount; } console.log(calculateTotalAmount(true)); //结果是0
const就比较好理解了,常量,一旦赋值就不能再改变了。
Classes(类)
ES6中添加了对类的支持,引入了class关键字(其实class在JavaScript中一直是保留字,目的就是考虑到可能在以后的新版本中会用到,现在终于派上用场了)。JS本身就是面向对象的,ES6中提供的类实际上只是JS原型模式的包装。现在提供原生的class支持后,对象的创建,继承更加直观了,并且父类方法的调用,实例化,静态方法和构造函数等概念都更加形象化:
//类的定义 class Animal { //ES6中新型构造器 constructor(name) { this.name = name; } //实例方法 sayName() { console.log('My name is '+this.name); } } //类的继承 class Programmer extends Animal { constructor(name) { //直接调用父类构造器进行初始化 super(name); } program() { console.log("I'm coding..."); } } //测试我们的类 var animal=new Animal('dummy'), wayou=new Programmer('wayou'); animal.sayName();//输出 ‘My name is dummy’ wayou.sayName();//输出 ‘My name is wayou’ wayou.program();//输出 ‘I'm coding...’
Modules(模块)
众所周知,在ES6以前JavaScript并不支持本地的模块。人们想出了AMD,RequireJS,CommonJS以及其它解决方法。现在ES6中可以用模块import 和export 操作了。
//module.js export var port = 3000; export function getAccounts(url) { ... } //main.js,引入module.js的东西 import {port, getAccounts} from 'module'; console.log(port); // 3000
或者我们可以在main.js中把整个模块导入, 并命名为 service:
import * as service from 'module'; console.log(service.port); // 3000
for of 值遍历
我们都知道for in 循环用于遍历数组,类数组或对象,ES6中新引入的for of循环功能相似,不同的是每次循环它提供的不是序号而是值。
var someArray = [ "a", "b", "c" ]; for (v of someArray) { console.log(v);//输出 a,b,c }