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重寫:

相關文章
相關標籤/搜索