如下是ES6排名前十的最佳特性列表(排名不分前後):javascript
【備註 】這裏只列出了10條比較經常使用的特性。並非全部的瀏覽器都支持ES6模塊,因此你須要使用一些像jspm去支持ES6模塊。java
ES5:node
var link = function (height, color, url) { var height = height || 50; var color = color || 'red'; var url = url || 'http://azat.co'; ... }
ES6:直接寫在參數裏nginx
var link = function(height = 50, color = 'red', url = 'http://azat.co') { ... }
好處
節省了代碼量。json
在字符串裏面輸出變量api
ES5:數組
var name = 'Your name is ' + first + ' ' + last + '.'; var url = 'http://localhost:3000/api/messages/' + id;
ES6:,使用新的語法 $ {NAME}
,並把它放在反引號裏:promise
var name = 'Your name is ${first} ${last}.'; var url = 'http://loalhost:3000/api/messages/${id}';
好處
: 這裏的$ {NAME}直接當作字符串用,無需寫加號瀏覽器
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'; var fourAgreements = 'You have the right to be you.n You can only be you when you do your best.';
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 theren Had worn them really about the same,`; var fourAgreements = `You have the right to be you.n You can only be you when you do your best.`;
好處
:直接一個反引號,將全部的字符串放進去便可,中介隨意換行,好清爽!
下邊例子中,house 和 mouse是 key,同時 house 和 mouse 也是一個變量。
ES5:
var data = $('body').data(), // data has properties house and mouse house = data.house, mouse = data.mouse;
以及在node.js中用ES5是這樣:
var jsonMiddleware = require('body-parser').jsonMiddleware ; var body = req.body, // body has username and password username = body.username, password = body.password;
ES6:
var {house,mouse} = $('body').data(); //we'll get house and mouse variables var {jsonMiddleware} = require('body-parser'); var {username,password} = req.body;
在數組中是這樣的:
var [col1,col2] = $('.column'), [line1,line2,line3, ,line5] = file.split('n');
好處
:使用{}省去了寫對象的屬性的步驟,固然這個{}中的變量是與對象的屬性名字保持一致的狀況下。
使用對象文本能夠作許多讓人意想不到的事情!經過ES6,咱們能夠把ES5中的JSON變得更加接近於一個類。
下面是一個典型ES5對象文本,裏面有一些方法和屬性: var serviceBase = {port: 3000, url: 'azat.co'}, getAccounts = function(){return [1,2,3]}; var accountServiceES5 = { port: serviceBase.port, url: serviceBase.url, getAccounts: getAccounts, toString: function() { return JSON.stringify(this.valueOf()); }, getUrl: function() {return "http://" + this.url + ':' + this.port}, valueOf_1_2_3: getAccounts() }
若是咱們想讓它更有意思,咱們能夠用Object.create從serviceBase繼承原型的方法: var accountServiceES5ObjectCreate = Object.create(serviceBase) // Object.create() 方法建立一個擁有指定原型和若干個指定屬性的對象。 var accountServiceES5ObjectCreate = { getAccounts: getAccounts, toString: function() { return JSON.stringify(this.valueOf()); }, getUrl: function() {return "http://" + this.url + ':' + this.port}, valueOf_1_2_3: getAccounts() }
ES6的對象文本中:既能夠直接分配getAccounts: getAccounts,也能夠只需用一個getAccounts
var serviceBase = {port: 3000, url: 'azat.co'}, getAccount = function(){return [1,2,3]}; var accountService = { __proto__: serviceBase, //經過proto設置屬性 getAccount, // 既能夠直接分配getAccounts: getAccounts,也能夠只需用一個getAccounts toString() { //這裏將json形式改成函數形式 return JSON.stringify(super.valueOf()); //調用super防範 }, getUrl() {return "http://" + this.url + ':' + this.port}, [ 'valueOf_' + getAccounts().join('_') ]: getAccounts() //使用動態key值(valueOf_1_2_3)此處將getAccounts()方法獲得的數組[1,2,3]轉化爲字符串1_2_3 }; console.log(accountService);
好處
:至關於直接將結果寫進去,而再也不必須 key:value
這些豐富的箭頭是使人驚訝的由於它們將使許多操做變成現實,好比,
之前咱們使用閉包,this老是預期以外地產生改變,而箭頭函數的迷人之處在於,如今你的this能夠按照你的預期使用了,身處箭頭函數裏面,this仍是原來的this。
ES5:
var _this = this; $('.btn').click(function(event){ _this.sendData(); })
ES6: 就不須要用 _this = this:
$('.btn').click((event) =>{ this.sendData(); })
再好比:
ES5:
ES6:咱們並不須要用_this浪費時間,如今你的this能夠按照你的預期使用了,身處箭頭函數裏面,this仍是原來的thisvar logUpperCase = function() { var _this = this; //this = Object {string: "ES6 ROCKS"} console.log('this指的是',this); //Object {string: "ES6 ROCKS"} console.log('_this指的是',_this);//Object {string: "ES6 ROCKS"} this.string = this.string.toUpperCase(); console.log(_this.string); //ES6 ROCKS console.log(this.string); //ES6 ROCKS return function () { return console.log(_this.string); //ES6 ROCKS return console.log(_this.string); //若是return _this.string,將返回 undefined,由於 } } logUpperCase.call({ string: 'ES6 rocks' })();
var logUpperCase = function() { this.string = this.string.toUpperCase();//this仍是原來的this return () => console.log(this.string); } logUpperCase.call({ string: 'ES6 rocks' })();
注意
只要你願意,在ES6中=>能夠混合和匹配老的函數一塊兒使用。當在一行代碼中用了箭頭函數,它就變成了一個表達式。它將暗地裏返回單個語句的結果。若是你超過了一行,將須要明確使用return。
ES5:
var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']; var messages = ids.map(function (value) { return "ID is " + value; // explicit return });
ES6:
var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']; var messages = ids.map((value) => `ID is ${value}`); //implicit return
好處
:
* 並不須要用_this浪費時間,如今你的this能夠按照你的預期使用了,身處箭頭函數裏面,this仍是原來的this。
* => 能夠代替function關鍵字,當在一行用了箭頭函數,能夠省去{},還能夠省去return,它會暗地裏返回的。
ES5:
setTimeout(function(){ console.log('Yay!'); }, 1000);
ES6: 咱們能夠用promise重寫
var wait1000 = new Promise((resolve,reject)=> { setTimeout(resolve,1000); }).then(()=> { console.log('Yay!'); });
若是咱們有更多的嵌套邏輯在setTimeout()回調函數中,好處會明顯一點:
ES5:
setTimeout(function(){ console.log('Yay!'); setTimeout(function(){ console.log('Wheeyee!'); }, 1000) }, 1000);
ES6: 咱們能夠用promise重寫
var wait1000 = ()=> new Promise((resolve,reject)=>{ setTimeout(resolve,1000);}); wait1000() .then(function(){ console.log('Yay!'); return wait1000() }) .then(function(){ console.log('Wheeyee!'); });
let是一種新的變量聲明方式,它容許你把變量做用域控制在塊級裏面。咱們用大括號定義代碼塊,在ES5中,塊級做用域起不了任何做用:
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
ES6: 用let限制塊級做用域
function calculateTotalAmount(vip){ var amouont = 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 由於塊做用域中有了let。
談到const,就更加容易了;它就是一個不變量,也是塊級做用域就像let同樣。
好處
: 咱們用let限制塊級做用域。而var是限制函數做用域。
ES6沒有用函數,而是使用原型實現類。咱們建立一個類baseModel ,而且在這個類裏定義了一個constructor 和一個 getName()方法:
class baseModel { constructor(options, data) {// class constructor, 注意咱們對options 和data使用了默認參數值。 this.name = 'Base'; this.url = 'http://azat.co/api'; this.data = data; this.options = options; } getName() { // class method console.log(`Class name: ${this.name}`); } getUrl() { // class method console.log(`Url: ${this.url}`); } }
AccountModel 從類baseModel 中繼承而來:
class AccountModel extends baseModel { constructor(options, data) { super({private: true}, ['32', '5242']); this.url +='/accounts/'; } get accountsData() { return this.data; } } // 調用 let accounts = new AccountModel(5); accounts.getName(); // Class name: Base console.log('Data is %s', accounts.accountsData); // Data is 32,5242 //子類必須在constructor方法中調用super方法,不然新建實例時會報錯。 //這是由於子類沒有本身的this對象,而是繼承父類的this對象,而後對其進行加工。 //若是不調用super方法,子類就得不到this對象。
【注意】:
* 此處的繼承中,子類必須在constructor方法中調用super方法,不然新建實例時會報錯。
* 此處的super方法繼承了父類的全部方法,包括不在父類的constructor中的其餘方法,固然能夠改寫父類方法,好比上述例子,繼承了getName(),getUrl()方法,以及constructor()中的this.name等屬性,同時改寫了this.url,增長了accountsData,且新增的方法前邊要加上get。
* 子類調用super方法能夠傳入參數,對應constructor()函數的形參。
ES5導出:
module.exports = { port: 3000, getAccounts: function() { ... }}
ES6導出:
export var port = 3000; export function getAccounts(url) { ...}
ES5導入:
var service = require('module.js'); console.log(service.port); // 3000
ES6導入:
咱們需用import {name} from ‘my-module’語法
import {port, getAccounts} from 'module'; console.log(port); // 300
或者ES6總體導入:
import * as service from 'module'; console.log(service.port); // 3000
這裏還有許多ES6的其它特性你可能會使用到,排名不分前後: