EcmaScript 6 十大经常使用特性

如下是ES6排名前十的最佳特性列表(排名不分前后):javascript

  1. Default Parameters(默认参数) in ES6
  2. Template Literals (模板文本)in ES6
  3. Multi-line Strings (多行字符串)in ES6
  4. Destructuring Assignment (解构赋值)in ES6
  5. Enhanced Object Literals (加强的对象文本)in ES6
  6. Arrow Functions (箭头函数)in ES6
  7. Promises in ES6
  8. Block-Scoped Constructs Let and Const(块做用域构造Let and Const)
  9. Classes(类) in ES6
  10. Modules(模块) in ES6

声明:这些列表仅是我的主观意见。它毫不是为了削弱ES6其它功能,这里只列出了10条比较经常使用的特性。html

1.Default Parameters(默认参数) in ES6

还记得咱们之前不得不经过下面方式来定义默认参数:java

1 var link = function (height, color, url) {
2     var height = height || 50;
3     var color = color || 'red';
4     var url = url || 'http://azat.co';
5     ...
6 }

一切工做都是正常的,直到参数值是0后,就有问题了,由于在JavaScript中,0表示fasly,它是默认被hard-coded的值,而不能变成参数自己的值。固然,若是你非要用0做为值,咱们能够忽略这一缺陷而且使用逻辑OR就好了!但在ES6,咱们能够直接把默认值放在函数申明里:node

1 var link = function(height = 50, color = 'red', url = 'http://azat.co') {
2   ...
3 }

顺便说一句,这个语法相似于Ruby!jquery

2.Template Literals(模板对象) in ES6

在其它语言中,使用模板和插入值是在字符串里面输出变量的一种方式。所以,在ES5,咱们能够这样组合一个字符串:webpack

1 var name = 'Your name is ' + first + ' ' + last + '.';
2 var url = 'http://localhost:3000/api/messages/' + id;

幸运的是,在ES6中,咱们可使用新的语法$ {NAME},并把它放在反引号里git

1 var name = `Your name is ${first} ${last}. `;
2 var url = `http://localhost:3000/api/messages/${id}`;

3.Multi-line Strings (多行字符串)in ES6

ES6的多行字符串是一个很是实用的功能。在ES5中,咱们不得不使用如下方法来表示多行字符串:es6

1 var roadPoem = 'Then took the other, as just as fair,nt'
2     + 'And having perhaps the better claimnt'
3     + 'Because it was grassy and wanted wear,nt'
4     + 'Though as for that the passing therent'
5     + 'Had worn them really about the same,nt';
6 var fourAgreements = 'You have the right to be you.n
7     You can only be you when you do your best.';

然而在ES6中,仅仅用反引号就能够解决了:github

1 var roadPoem = `Then took the other, as just as fair,
2     And having perhaps the better claim
3     Because it was grassy and wanted wear,
4     Though as for that the passing there
5     Had worn them really about the same,`;
6 var fourAgreements = `You have the right to be you.
7     You can only be you when you do your best.`;

4.Destructuring Assignment (解构赋值)in ES6

解构多是一个比较难以掌握的概念。先从一个简单的赋值讲起,其中house 和 mouse是key,同时house 和mouse也是一个变量,在ES5中是这样:web

1 var data = $('body').data(), // data has properties house and mouse
2    house = data.house,
3    mouse = data.mouse;

以及在node.js中用ES5是这样:

1 var jsonMiddleware = require('body-parser').jsonMiddleware ;
2 var body = req.body, // body has username and password
3    username = body.username,
4    password = body.password;

在ES6,咱们可使用这些语句代替上面的ES5代码:

1 var { house, mouse} = $('body').data(); // we'll get house and mouse variables
2 var {jsonMiddleware} = require('body-parser');
3 var {username, password} = req.body;

这个一样也适用于数组,很是赞的用法:

1 var [col1, col2]  = $('.column'),
2    [line1, line2, line3, , line5] = file.split('n');

咱们可能须要一些时间来习惯解构赋值语法的使用,可是它确实能给咱们带来许多意外的收获。

5.Enhanced Object Literals (加强的对象字面量)in ES6

使用对象文本能够作许多让人意想不到的事情!经过ES6,咱们能够把ES5中的JSON变得更加接近于一个类。

下面是一个典型ES5对象文本,里面有一些方法和属性:

 1 var serviceBase = {port: 3000, url: 'azat.co'},
 2     getAccounts = function(){return [1,2,3]};
 3 var accountServiceES5 = {
 4   port: serviceBase.port,
 5   url: serviceBase.url,
 6   getAccounts: getAccounts,
 7    toString: function() {
 8       return JSON.stringify(this.valueOf());
 9   },
10   getUrl: function() {return "http://" + this.url + ':' + this.port},
11   valueOf_1_2_3: getAccounts()
12 }

若是咱们想让它更有意思,咱们能够用Object.create从serviceBase继承原型的方法:

1 var accountServiceES5ObjectCreate = Object.create(serviceBase)
2 var accountServiceES5ObjectCreate = {
3   getAccounts: getAccounts,
4   toString: function() {
5     return JSON.stringify(this.valueOf());
6   },
7   getUrl: function() {return "http://" + this.url + ':' + this.port},
8   valueOf_1_2_3: getAccounts()
9 }

咱们知道,accountServiceES5ObjectCreate 和accountServiceES5 并非彻底一致的,由于一个对象(accountServiceES5)在__proto__对象中将有下面这些属性:

 

为了方便举例,咱们将考虑它们的类似处。因此在ES6的对象文本中,既能够直接分配getAccounts: getAccounts,也能够只需用一个getAccounts,此外,咱们在这里经过__proto__(并非经过’proto’)设置属性,以下所示:

1 var serviceBase = {port: 3000, url: 'azat.co'},
2 getAccounts = function(){return [1,2,3]};
3 var accountService = {
4     __proto__: serviceBase,
5     getAccounts,

另外,咱们能够调用super防范,以及使用动态key值(valueOf_1_2_3):

1 toString() {
2      return JSON.stringify((super.valueOf()));
3     },
4     getUrl() {return "http://" + this.url + ':' + this.port},
5     [ 'valueOf_' + getAccounts().join('_') ]: getAccounts()
6 };
7 console.log(accountService)

 

ES6对象文本是一个很大的进步对于旧版的对象文原本说。

6.Arrow Functions in(箭头函数) ES6

这是我火烧眉毛想讲的一个特征,CoffeeScript 就是由于它丰富的箭头函数让不少开发者喜好。在ES6中,也有了丰富的箭头函数。这些丰富的箭头是使人惊讶的由于它们将使许多操做变成现实,好比,

之前咱们使用闭包,this老是预期以外地产生改变,而箭头函数的迷人之处在于,如今你的this能够按照你的预期使用了,身处箭头函数里面,this仍是原来的this。

有了箭头函数在ES6中, 咱们就没必要用that = this或 self =  this  或 _this = this  或.bind(this)。例如,下面的代码用ES5就不是很优雅:

1 var _this = this;
2 $('.btn').click(function(event){
3   _this.sendData();
4 })

在ES6中就不须要用 _this = this:

1 $('.btn').click((event) =>{
2   this.sendData();
3 })

不幸的是,ES6委员会决定,之前的function的传递方式也是一个很好的方案,因此它们仍然保留了之前的功能。

下面这是一个另外的例子,咱们经过call传递文本给logUpperCase() 函数在ES5中:

 1 var logUpperCase = function() {
 2   var _this = this;
 3  
 4   this.string = this.string.toUpperCase();
 5   return function () {
 6     return console.log(_this.string);
 7   }
 8 }
 9  
10 logUpperCase.call({ string: 'ES6 rocks' })();

而在ES6,咱们并不须要用_this浪费时间:

1 var logUpperCase = function() {
2   this.string = this.string.toUpperCase();
3   return () => console.log(this.string);
4 }
5 logUpperCase.call({ string: 'ES6 rocks' })();

请注意,只要你愿意,在ES6中=>能够混合和匹配老的函数一块儿使用。当在一行代码中用了箭头函数,它就变成了一个表达式。它将暗地里返回单个语句的结果。若是你超过了一行,将须要明确使用return。

这是用ES5代码建立一个消息数组:

1 var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9'];
2 var messages = ids.map(function (value) {
3   return "ID is " + value; // explicit return
4 });

用ES6是这样:

1 var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9'];
2 var messages = ids.map(value => `ID is ${value}`); // implicit return

请注意,这里用了字符串模板。

在箭头函数中,对于单个参数,括号()是可选的,但当你超过一个参数的时候你就须要他们。

在ES5代码有明确的返回功能:

1 var ids = ['5632953c4e345e145fdf2df8', '563295464e345e145fdf2df9'];
2 var messages = ids.map(function (value, index, list) {
3   return 'ID of ' + index + ' element is ' + value + ' '; // explicit return
4 });

在ES6中有更加严谨的版本,参数须要被包含在括号里而且它是隐式的返回:

1 var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9'];
2 var messages = ids.map((value, index, list) => `ID of ${index} element is ${value} `); // implicit return

7. Promises in ES6

Promises 是一个有争议的话题。所以有许多略微不一样的promise 实现语法。Q,bluebird,deferred.js,vow, avow, jquery 一些能够列出名字的。也有人说咱们不须要promises,仅仅使用异步,生成器,回调等就够了。但使人高兴的是,在ES6中有标准的Promise实现。

下面是一个简单的用setTimeout()实现的异步延迟加载函数:

1 setTimeout(function(){
2   console.log('Yay!');
3 }, 1000);

在ES6中,咱们能够用promise重写:

相关文章
相关标签/搜索