
在這篇文章里,我將演示 6 種 ES6 新特性的使用技巧。
通過參數(shù)默認值強制要求傳參 ES6 指定默認參數(shù)在它們被實際使用的時候才會被執(zhí)行,這個特性讓我們可以強制要求傳參: /** * Called if a parameter is missing and * the default value is evaluated. */ function mandatory() { throw new Error('Missing parameter'); } function foo(mustBeProvided = mandatory()) { return mustBeProvided; }
函數(shù)調(diào)用 mandatory() 只有在參數(shù) mustBeProvided 缺失的時候才會被執(zhí)行。
在控制臺測試: > foo() Error: Missing parameter > foo(123) 123
通過 for-of 循環(huán)來遍歷數(shù)組元素和索引
方法 forEach() 允許你遍歷一個數(shù)組的元素和索引: 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 循環(huán)支持 ES6 迭代(通過 iterables 和 iterators)和解構。如果你通過數(shù)組的新方法 enteries() 再結合解構,可以達到上面 forEach 同樣的效果: const arr = ['a', 'b', 'c']; for (const [index, elem] of arr.entries()) { console.log(`index = ${index}, elem = ${elem}`); }
arr.enteries() 通過索引-元素配對返回一個可迭代對象。然后通過解構數(shù)組 [index, elem] 直接得到每一對元素和索引。console.log() 的參數(shù)是 ES6 中的模板字面量特性,這個特性帶給字符串解析模板變量的能力。
更多內(nèi)容: 章節(jié): “Destructuring” 章節(jié): “Iterables and iterators” 段落: “Iterating with a destructuring pattern” 章節(jié): “Template literals”
遍歷 Unicode 表示的字符串
一些 Unicode 編碼的字由兩個 JavaScript 字符組成,例如,emoji 表情:
字符串實現(xiàn)了 ES6 迭代,如果你通過迭代來訪問字符串,你可以獲得編碼過的單個字(每個字用 1 或 2 個 JavaScript 字符表示)。例如: for (const ch of 'x\uD83D\uDE80y') { console.log(ch.length); } // Output: // 1 // 2 // 1
這讓你能夠很方便地得到一個字符串中實際的字數(shù): > [...'x\uD83D\uDE80y'].length 3
展開操作符 (...) 將它的操作對象展開并插入數(shù)組。
通過變量解構交換兩個變量的值
如果你將一對變量放入一個數(shù)組,然后將數(shù)組解構賦值相同的變量(順序不同),你就可以不依賴中間變量交換兩個變量的值: [a, b] = [b, a];
可以想象,JavaScript 引擎在未來將會針對這個模式進行特別優(yōu)化,去掉構造數(shù)組的開銷。
通過模板字面量(template literals)進行簡單的模板解析
ES6 的模板字面量與文字模板相比,更接近于字符串字面量。但是,如果你將它們通過函數(shù)返回,你可以使用他們來做簡單的模板渲染: const tmpl = addrs => ` <table> ${addrs.map(addr => ` <tr><td>${addr.first}</td></tr> <tr><td>${addr.last}</td></tr> `).join('')} </table> `;
tmpl 函數(shù)將數(shù)組 addrs 用 map(通過箭頭函數(shù)) join 拼成字符串。tmpl() 可以批量插入數(shù)據(jù)到表格中: const data = [ { first: '<Jane>', last: 'Bond' }, { first: 'Lars', last: '<Croft>' }, ]; console.log(tmpl(data)); // Output: // <table> // // <tr><td><Jane></td></tr> // <tr><td>Bond</td></tr> // // <tr><td>Lars</td></tr> // <tr><td><Croft></td></tr> // // </table>
通過子類工廠實現(xiàn)簡單的合成器
當 ES6 類繼承另一個類,被繼承的類可以是通過任意表達式創(chuàng)建的動態(tài)類: // Function id() simply returns its parameter const id = x => x;
class Foo extends id(Object) {}
這個特性可以允許你實現(xiàn)一種合成器模式,用一個函數(shù)來將一個類 C 映射到一個新的繼承了C的類。例如,下面的兩個函數(shù) Storage 和 Validation 是合成器: const Storage = Sup => class extends Sup { save(database) { ··· } }; const Validation = Sup => class extends Sup { validate(schema) { ··· } };
你可以使用它們?nèi)ソM合生成一個如下的 Employee 類: class Person { ··· } class Employee extends Storage(Validation(Person)) { ··· }
|