1. 程式人生 > >10個最佳ES6特性

10個最佳ES6特性

譯者按: 人生苦短,我用ES6

為了保證可讀性,本文采用意譯而非直譯,並且對原始碼進行了大量修改。另外,本文版權歸原作者所有,翻譯僅用於學習。

小編推薦:Fundebug專注於JavaScript、微信小程式、微信小遊戲,Node.js和Java線上bug實時監控。真的是一個很好用的bug監控服務,眾多大佬公司都在使用。

ES6,正式名稱是ECMAScript2015,但是ES6這個名稱更加簡潔。ES6已經不再是JavaScript最新的標準,但是它已經廣泛用於程式設計實踐中。如果你還沒用過ES6

,現在還不算太晚...

下面是10個ES6最佳特性,排名不分先後:

  • 函式引數預設值
  • 模板字串
  • 多行字串
  • 解構賦值
  • 物件屬性簡寫
  • 箭頭函式
  • Promise
  • Let與Const
  • 模組化

1. 函式引數預設值

不使用ES6

為函式的引數設定預設值:

function foo(height, color)
{
    var height = height || 50;
    var color = color || 'red';
    //...
}

這樣寫一般沒問題,但是,當引數的布林值為false時,是會出事情的!比如,我們這樣呼叫foo

函式:

foo(0, "", "")

因為0的布林值為false,這樣height的取值將是50。同理color的取值為'red'

使用ES6

function foo(height = 50, color = 'red')
{
    // ...
}

2. 模板字串

不使用ES6

使用+號將變數拼接為字串:

var name = 'Your name is ' + first + ' ' + last + '.'

使用ES6

將變數放在大括號之中:

var name = `Your name is ${first} ${last}.`

ES6的寫法更加簡潔、直觀。

3. 多行字串

不使用ES6

使用"\n\t"將多行字串拼接起來:

var roadPoem = 'Then took the other, as just as fair,\n\t'
    + 'And having perhaps the better claim\n\t'
    + 'Because it was grassy and wanted wear,\n\t'
    + 'Though as for that the passing there\n\t'
    + 'Had worn them really about the same,\n\t'

使用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,`

4. 解構賦值

不使用ES6

當需要獲取某個物件的屬性值時,需要單獨獲取:

var data = $('body').data(); // data有house和mouse屬性
var house = data.house;
var mouse = data.mouse;

使用ES6

一次性獲取物件的子屬性:

var { house, mouse} = $('body').data()

對於陣列也是一樣的:

var [col1, col2]  = $('.column');

5. 物件屬性簡寫

不使用ES6

物件中必須包含屬性和值,顯得非常多餘:

var bar = 'bar';
var foo = function ()
{
    // ...
}

var baz = {
  bar: bar,
  foo: foo
};

使用ES6

物件中直接寫變數,非常簡單:

var bar = 'bar';
var foo = function ()
{
    // ...
}

var baz = { bar, foo };

6. 箭頭函式

不使用ES6

普通函式體內的this,指向呼叫時所在的物件。

function foo() 
{
    console.log(this.id);
}

var id = 1;

foo(); // 輸出1

foo.call({ id: 2 }); // 輸出2

使用ES6

箭頭函式體內的this,就是定義時所在的物件,而不是呼叫時所在的物件。

var foo = () => {
  console.log(this.id);
}

var id = 1;

foo(); // 輸出1

foo.call({ id: 2 }); // 輸出1

7. Promise

不使用ES6

巢狀兩個setTimeout回撥函式:

setTimeout(function()
{
    console.log('Hello'); // 1秒後輸出"Hello"
    setTimeout(function()
    {
        console.log('Fundebug'); // 2秒後輸出"Fundebug"
    }, 1000);
}, 1000);

使用ES6

使用兩個then是非同步程式設計序列化,避免了回撥地獄:

var wait1000 = new Promise(function(resolve, reject)
{
    setTimeout(resolve, 1000);
});

wait1000
    .then(function()
    {
        console.log("Hello"); // 1秒後輸出"Hello"
        return wait1000;
    })
    .then(function()
    {
        console.log("Fundebug"); // 2秒後輸出"Fundebug"
    });

8. Let與Const

使用Var

var定義的變數未函式級作用域:

{
  var a = 10;
}

console.log(a); // 輸出10

使用let與const

let定義的變數為塊級作用域,因此會報錯:(如果你希望實時監控JavaScript應用的錯誤,歡迎免費使用Fundebug)

{
  let a = 10;
}

console.log(a); // 報錯“ReferenceError: a is not defined”

constlet一樣,也是塊級作用域。

9. 類

不使用ES6

使用建構函式建立物件:

function Point(x, y)
{
    this.x = x;
    this.y = y;
    this.add = function()
    {
        return this.x + this.y;
    };
}

var p = new Point(1, 2);

console.log(p.add()); // 輸出3

使用ES6

使用Class定義類,更加規範,且你能夠繼承:

class Point
{
    constructor(x, y)
    {
        this.x = x;
        this.y = y;
    }

    add()
    {
        return this.x + this.y;
    }
}

var p = new Point(1, 2);

console.log(p.add()); // 輸出3

10. 模組化

JavaScript一直沒有官方的模組化解決方案,開發者在實踐中主要採用CommonJSAMD規範。而ES6制定了模組(Module)功能。

不使用ES6

Node.js採用CommenJS規範實現了模組化,而前端也可以採用,只是在部署時需要使用Browserify等工具打包。這裡不妨介紹一下CommenJS規範。

module.js中使用module.exports匯出port變數和getAccounts函式:

module.exports = {
  port: 3000,
  getAccounts: function() {
    ...
  }
}

main.js中使用require匯入module.js

var service = require('module.js')
console.log(service.port) // 輸出3000

使用ES6

ES6中使用exportimport關鍵詞實現模組化。

module.js中使用export匯出port變數和getAccounts函式:

export var port = 3000
export function getAccounts(url) {
  ...
}

main.js中使用import匯入module.js,可以指定需要匯入的變數:

import {port, getAccounts} from 'module'
console.log(port) // 輸出3000

也可以將全部變數匯入:

import * as service from 'module'
console.log(service.port) // 3000

參考連結

Fundebug專注於JavaScript、微信小程式、微信小遊戲、支付寶小程式、React Native、Node.js和Java實時BUG監控。 自從2016年雙十一正式上線,Fundebug累計處理了7億+錯誤事件,得到了Google、360、金山軟體、百姓網等眾多知名使用者的認可。歡迎免費試用!

版權宣告

轉載時請註明作者Fundebug以及本文地址:
https://blog.fundebug.com/2017/08/21/10-best-es6-feature/