六個漂亮的 ES6 技巧

經過參數默認值強制要求傳參數組

 

ES6 指定默認參數在它們被實際使用的時候纔會被執行,這個特性讓咱們能夠強制要求傳參:ide

 

/**函數

* Called if a parameter is missing and測試

* the default value is evaluated.優化

*/ui

function mandatory() {編碼

    throw new Error("Missing parameter");lua

}spa

function foo(mustBeProvided = mandatory()) {code

    return mustBeProvided;

}

 

函數調用 mandatory() 只有在參數 mustBeProvided 缺失的時候纔會被執行。

 

在控制檯測試:

 

> foo()

Error: Missing parameter

> foo(123)

123

 

更多內容:

 

  • 段落: 「Required parameters」 。

 

經過 for-of 循環來遍歷數組元素和索引

 

方法 forEach() 容許你遍歷一個數組的元素和索引:

 

var arr = ["a", "b", "c"];

arr.forEach(function (elem, index) {

    console.log("index = "+index+", elem = "+elem);

});

// Output:

// index = 0, elem = a

// index = 1, elem = b

// index = 2, elem = c

 

ES6 的 for-of 循環支持 ES6 迭代(經過 iterables 和 iterators)和解構。若是你經過數組的新方法 enteries() 再結合解構,能夠達到上面 forEach 一樣的效果:

 

const arr = ["a", "b", "c"];

for (const [index, elem] of arr.entries()) {

    console.log(`index = ${index}, elem = ${elem}`);

}

 

arr.enteries() 經過索引-元素配對返回一個可迭代對象。而後經過解構數組 [index, elem] 直接獲得每一對元素和索引。console.log() 的參數是 ES6 中的模板字面量特性,這個特性帶給字符串解析模板變量的能力。

 

更多內容:

 

  • 章節: 「Destructuring」

  • 章節: 「Iterables and iterators」

  • 段落: 「Iterating with a destructuring pattern」

  • 章節: 「Template literals」

 

遍歷 Unicode 表示的字符串

 

一些 Unicode 編碼的字由兩個 JavaScript 字符組成,例如,emoji 表情:

 

 

字符串實現了 ES6 迭代,若是你經過迭代來訪問字符串,你能夠得到編碼過的單個字(每一個字用 1 或 2 個 JavaScript 字符表示)。例如:

 

for (const ch of "xuD83DuDE80y") {

    console.log(ch.length);

}

// Output:

// 1

// 2

// 1

 

這讓你可以很方便地獲得一個字符串中實際的字數:

 

> [..."xuD83DuDE80y"].length

3

 

展開操做符 (...) 將它的操做對象展開並插入數組。

 

更多內容:

 

  • 章節: 「Unicode in ES6」

  • 段落: 「The spread operator (...)」

 

經過變量解構交換兩個變量的值

 

若是你將一對變量放入一個數組,而後將數組解構賦值相同的變量(順序不一樣),你就能夠不依賴中間變量交換兩個變量的值:

 

[a, b] = [b, a];

 

能夠想象,JavaScript 引擎在將來將會針對這個模式進行特別優化,去掉構造數組的開銷。

 

更多內容:

 

  • 章節: 「Destructuring」

 

經過模板字面量(template literals)進行簡單的模板解析

 

ES6 的模板字面量與文字模板相比,更接近於字符串字面量。可是,若是你將它們經過函數返回,你可使用他們來作簡單的模板渲染:

 

const tmpl = addrs => `

    

    ${addrs.map(addr => `

        ${addr.first}${addr.last}

    `).join("")}

    

`;

 

tmpl 函數將數組 addrs 用 map(經過箭頭函數) join 拼成字符串。tmpl() 能夠批量插入數據到表格中:

 

const data = [

    { first: "", last: "Bond" },

    { first: "Lars", last: "" },

];

console.log(tmpl(data));

// Output:

// //

//    

//     Bond

//

//     Lars

//    

//

//

 

更多內容:

 

  • 博客文章: 「Handling whitespace in ES6 template literals」

  • 段落: 「Text templating via untagged template literals」

  • 章節: 「Arrow functions」

 

經過子類工廠實現簡單的合成器

 

當 ES6 類繼承另外一個類,被繼承的類能夠是經過任意表達式建立的動態類:

 

// Function id() simply returns its parameter

const id = x => x;

 

class Foo extends id(Object) {}

 

這個特性能夠容許你實現一種合成器模式,用一個函數來將一個類 C 映射到一個新的繼承了C的類。例如,下面的兩個函數 Storage 和 Validation 是合成器:

 

const Storage = Sup => class extends Sup {

    save(database) { ··· }

};

const Validation = Sup => class extends Sup {

    validate(schema) { ··· }

};

 

你可使用它們去組合生成一個以下的 Employee 類:

 

class Person { ··· }

class Employee extends Storage(Validation(Person)) { ··· }

 

更多信息:

 

  • 段落: 「Simple mixins」

下面的兩個章節提供了很好地歸納了 ECMAScript 6 的特性:

  • An overview of what’s new in ES6

  • First steps with ECMAScript 6 [features that are easy to adopt]

相關文章
相關標籤/搜索