ES6 完全使用手冊
- 這裡的 "ES6" 泛指 ES5 之後的新語法
- 這裡的 "完全" 是指本文會不斷更新
- 這裡的 "使用" 是指本文會展示很多 ES6 的使用場景
- 這裡的 "手冊" 是指你可以參照本文將專案更多的重構為 ES6 語法
此外還要注意這裡不一定就是正式進入規範的語法。
1. let 和 const
在我們開發的時候,可能認為應該預設使用 let 而不是 var,這種情況下,對於需要防寫的變數要使用 const。
然而另一種做法日益普及:預設使用 const,只有當確實需要改變變數的值的時候才使用 let。這是因為大部分的變數的值在初始化後不應再改變,而預料之外的變數的修改是很多 bug 的源頭。
// 例子 1-1 // bad var foo = 'bar'; // good let foo = 'bar'; // better const foo = 'bar'; 複製程式碼
2. 模板字串
1. 模板字串
需要拼接字串的時候儘量改成使用模板字串:
// 例子 2-1 // bad const foo = 'this is a' + example; // good const foo = `this is a ${example}`; 複製程式碼
2. 標籤模板
可以藉助標籤模板優化書寫方式:
// 例子 2-2 let url = oneLine ` www.taobao.com/example/index.html ?foo=${foo} &bar=${bar} `; console.log(url); // www.taobao.com/example/index.html?foo=foo&bar=bar 複製程式碼
oneLine 的原始碼可以參考ofollow,noindex">《ES6 系列之模板字串》
3. 箭頭函式
優先使用箭頭函式,不過以下幾種情況避免使用:
1. 使用箭頭函式定義物件的方法
// 例子 3-1 // bad let foo = { value: 1, getValue: () => console.log(this.value) } foo.getValue();// undefined 複製程式碼
2. 定義原型方法
// 例子 3-2 // bad function Foo() { this.value = 1 } Foo.prototype.getValue = () => console.log(this.value) let foo = new Foo() foo.getValue();// undefined 複製程式碼
3. 作為事件的回撥函式
// 例子 3-3 // bad const button = document.getElementById('myButton'); button.addEventListener('click', () => { console.log(this === window); // => true this.innerHTML = 'Clicked button'; }); 複製程式碼
4. Symbol
1. 唯一值
// 例子 4-1 // bad // 1. 建立的屬性會被 for-in 或 Object.keys() 枚舉出來 // 2. 一些庫可能在將來會使用同樣的方式,這會與你的程式碼發生衝突 if (element.isMoving) { smoothAnimations(element); } element.isMoving = true; // good if (element.__$jorendorff_animation_library$PLEASE_DO_NOT_USE_THIS_PROPERTY$isMoving__) { smoothAnimations(element); } element.__$jorendorff_animation_library$PLEASE_DO_NOT_USE_THIS_PROPERTY$isMoving__ = true; // better var isMoving = Symbol("isMoving"); ... if (element[isMoving]) { smoothAnimations(element); } element[isMoving] = true; 複製程式碼
2. 魔術字串
魔術字串指的是在程式碼之中多次出現、與程式碼形成強耦合的某一個具體的字串或者數值。
魔術字串不利於修改和維護,風格良好的程式碼,應該儘量消除魔術字串,改由含義清晰的變數代替。
// 例子 4-1 // bad const TYPE_AUDIO = 'AUDIO' const TYPE_VIDEO = 'VIDEO' const TYPE_IMAGE = 'IMAGE' // good const TYPE_AUDIO = Symbol() const TYPE_VIDEO = Symbol() const TYPE_IMAGE = Symbol() function handleFileResource(resource) { switch(resource.type) { case TYPE_AUDIO: playAudio(resource) break case TYPE_VIDEO: playVideo(resource) break case TYPE_IMAGE: previewImage(resource) break default: throw new Error('Unknown type of resource') } } 複製程式碼
3. 私有變數
Symbol 也可以用於私有變數的實現。
// 例子 4-3 const Example = (function() { var _private = Symbol('private'); class Example { constructor() { this[_private] = 'private'; } getName() { return this[_private]; } } return Example; })(); var ex = new Example(); console.log(ex.getName()); // private console.log(ex.name); // undefined 複製程式碼
5. Set 和 Map
1. 陣列去重
// 例子 5-1 [...new Set(array)] 複製程式碼
2. 條件語句的優化
// 例子 5-2 // 根據顏色找出對應的水果 // bad function test(color) { switch (color) { case 'red': return ['apple', 'strawberry']; case 'yellow': return ['banana', 'pineapple']; case 'purple': return ['grape', 'plum']; default: return []; } } test('yellow'); // ['banana', 'pineapple'] 複製程式碼
// good const fruitColor = { red: ['apple', 'strawberry'], yellow: ['banana', 'pineapple'], purple: ['grape', 'plum'] }; function test(color) { return fruitColor[color] || []; } 複製程式碼
// better const fruitColor = new Map() .set('red', ['apple', 'strawberry']) .set('yellow', ['banana', 'pineapple']) .set('purple', ['grape', 'plum']); function test(color) { return fruitColor.get(color) || []; } 複製程式碼
6. for of
1. 遍歷範圍
for...of 迴圈可以使用的範圍包括:
- 陣列
- Set
- Map
- 類陣列物件,如 arguments 物件、DOM NodeList 物件
- Generator 物件
- 字串
2. 優勢
ES2015 引入了 for..of 迴圈,它結合了 forEach 的簡潔性和中斷迴圈的能力:
// 例子 6-1 for (const v of ['a', 'b', 'c']) { console.log(v); } // a b c for (const [i, v] of ['a', 'b', 'c'].entries()) { console.log(i, v); } // 0 "a" // 1 "b" // 2 "c" 複製程式碼
3. 遍歷 Map
// 例子 6-2 let map = new Map(arr); // 遍歷 key 值 for (let key of map.keys()) { console.log(key); } // 遍歷 value 值 for (let value of map.values()) { console.log(value); } // 遍歷 key 和 value 值(一) for (let item of map.entries()) { console.log(item[0], item[1]); } // 遍歷 key 和 value 值(二) for (let [key, value] of data) { console.log(key) } 複製程式碼
7. Promise
1. 基本示例
// 例子 7-1 // bad request(url, function(err, res, body) { if (err) handleError(err); fs.writeFile('1.txt', body, function(err) { request(url2, function(err, res, body) { if (err) handleError(err) }) }) }); // good request(url) .then(function(result) { return writeFileAsynv('1.txt', result) }) .then(function(result) { return request(url2) }) .catch(function(e){ handleError(e) }); 複製程式碼
2. finally
// 例子 7-2 fetch('file.json') .then(data => data.json()) .catch(error => console.error(error)) .finally(() => console.log('finished')); 複製程式碼
8. Async
1. 程式碼更加簡潔
// 例子 8-1 // good function fetch() { return ( fetchData() .then(() => { return "done" }); ) } // better async function fetch() { await fetchData() return "done" }; 複製程式碼
// 例子 8-2 // good function fetch() { return fetchData() .then(data => { if (data.moreData) { return fetchAnotherData(data) .then(moreData => { return moreData }) } else { return data } }); } // better async function fetch() { const data = await fetchData() if (data.moreData) { const moreData = await fetchAnotherData(data); return moreData } else { return data } }; 複製程式碼
// 例子 8-3 // good function fetch() { return ( fetchData() .then(value1 => { return fetchMoreData(value1) }) .then(value2 => { return fetchMoreData2(value2) }) ) } // better async function fetch() { const value1 = await fetchData() const value2 = await fetchMoreData(value1) return fetchMoreData2(value2) }; 複製程式碼
2. 錯誤處理
// 例子 8-4 // good function fetch() { try { fetchData() .then(result => { const data = JSON.parse(result) }) .catch((err) => { console.log(err) }) } catch (err) { console.log(err) } } // better async function fetch() { try { const data = JSON.parse(await fetchData()) } catch (err) { console.log(err) } }; 複製程式碼
3. "async 地獄"
// 例子 8-5 // bad (async () => { const getList = await getList(); const getAnotherList = await getAnotherList(); })(); // good (async () => { const listPromise = getList(); const anotherListPromise = getAnotherList(); await listPromise; await anotherListPromise; })(); // good (async () => { Promise.all([getList(), getAnotherList()]).then(...); })(); 複製程式碼
9. Class
建構函式儘可能使用 Class 的形式
// 例子 9-1 class Foo { static bar () { this.baz(); } static baz () { console.log('hello'); } baz () { console.log('world'); } } Foo.bar(); // hello 複製程式碼
// 例子 9-2 class Shape { constructor(width, height) { this._width = width; this._height = height; } get area() { return this._width * this._height; } } const square = new Shape(10, 10); console.log(square.area);// 100 console.log(square._width);// 10 複製程式碼
10.Decorator
1. log
// 例子 10-1 class Math { @log add(a, b) { return a + b; } } 複製程式碼
log 的實現可以參考《ES6 系列之我們來聊聊裝飾器》
2. autobind
// 例子 10-2 class Toggle extends React.Component { @autobind handleClick() { console.log(this) } render() { return ( <button onClick={this.handleClick}> button </button> ); } } 複製程式碼
autobind 的實現可以參考《ES6 系列之我們來聊聊裝飾器》
3. debounce
// 例子 10-3 class Toggle extends React.Component { @debounce(500, true) handleClick() { console.log('toggle') } render() { return ( <button onClick={this.handleClick}> button </button> ); } } 複製程式碼
debounce 的實現可以參考《ES6 系列之我們來聊聊裝飾器》
4. React 與 Redux
// 例子 10-4 // good class MyReactComponent extends React.Component {} export default connect(mapStateToProps, mapDispatchToProps)(MyReactComponent); // better @connect(mapStateToProps, mapDispatchToProps) export default class MyReactComponent extends React.Component {}; 複製程式碼
11. 函式
1. 預設值
// 例子 11-1 // bad function test(quantity) { const q = quantity || 1; } // good function test(quantity = 1) { ... } 複製程式碼
// 例子 11-2 doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 }); // bad function doSomething(config) { const foo = config.foo !== undefined ? config.foo : 'Hi'; const bar = config.bar !== undefined ? config.bar : 'Yo!'; const baz = config.baz !== undefined ? config.baz : 13; } // good function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) { ... } // better function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) { ... } 複製程式碼
// 例子 11-3 // bad const Button = ({className}) => { const classname = className || 'default-size'; return <span className={classname}></span> }; // good const Button = ({className = 'default-size'}) => ( <span className={classname}></span> ); // better const Button = ({className}) => <span className={className}></span> } Button.defaultProps = { className: 'default-size' } 複製程式碼
// 例子 11-4 const required = () => {throw new Error('Missing parameter')}; const add = (a = required(), b = required()) => a + b; add(1, 2) // 3 add(1); // Error: Missing parameter. 複製程式碼
12. 拓展運算子
1. arguments 轉陣列
// 例子 12-1 // bad function sortNumbers() { return Array.prototype.slice.call(arguments).sort(); } // good const sortNumbers = (...numbers) => numbers.sort(); 複製程式碼
2. 呼叫引數
// 例子 12-2 // bad Math.max.apply(null, [14, 3, 77]) // good Math.max(...[14, 3, 77]) // 等同於 Math.max(14, 3, 77); 複製程式碼
3. 構建物件
剔除部分屬性,將剩下的屬性構建一個新的物件
// 例子 12-3 let [a, b, ...arr] = [1, 2, 3, 4, 5]; const { a, b, ...others } = { a: 1, b: 2, c: 3, d: 4, e: 5 }; 複製程式碼
有條件的構建物件
// 例子 12-4 // bad function pick(data) { const { id, name, age} = data const res = { guid: id } if (name) { res.name = name } else if (age) { res.age = age } return res } // good function pick({id, name, age}) { return { guid: id, ...(name && {name}), ...(age && {age}) } } 複製程式碼
合併物件
// 例子 12-5 let obj1 = { a: 1, b: 2,c: 3 } let obj2 = { b: 4, c: 5, d: 6} let merged = {...obj1, ...obj2}; 複製程式碼
4. React
將物件全部傳入元件
// 例子 12-6 const parmas ={value1: 1, value2: 2, value3: 3} <Test {...parmas} /> 複製程式碼
13. 雙冒號運算子
// 例子 13-1 foo::bar; // 等同於 bar.bind(foo); foo::bar(...arguments); // 等同於 bar.apply(foo, arguments); 複製程式碼
如果雙冒號左邊為空,右邊是一個物件的方法,則等於將該方法繫結在該物件上面。
// 例子 13-2 var method = obj::obj.foo; // 等同於 var method = ::obj.foo; let log = ::console.log; // 等同於 var log = console.log.bind(console); 複製程式碼
14. 解構賦值
1. 物件的基本解構
// 例子 14-1 componentWillReceiveProps(newProps) { this.setState({ active: newProps.active }) } componentWillReceiveProps({active}) { this.setState({active}) } 複製程式碼
// 例子 14-2 // bad handleEvent = () => { this.setState({ data: this.state.data.set("key", "value") }) }; // good handleEvent = () => { this.setState(({data}) => ({ data: data.set("key", "value") })) }; 複製程式碼
// 例子 14-3 Promise.all([Promise.resolve(1), Promise.resolve(2)]) .then(([x, y]) => { console.log(x, y); }); 複製程式碼
2. 物件深度解構
// 例子 14-4 // bad function test(fruit) { if (fruit && fruit.name){ console.log (fruit.name); } else { console.log('unknown'); } } // good function test({name} = {}) { console.log (name || 'unknown'); } 複製程式碼
// 例子 14-5 let obj = { a: { b: { c: 1 } } }; const {a: {b: {c = ''} = ''} = ''} = obj; 複製程式碼
3. 陣列解構
// 例子 14-6 // bad const spliteLocale = locale.splite("-"); const language = spliteLocale[0]; const country = spliteLocale[1]; // good const [language, country] = locale.splite('-'); 複製程式碼
4. 變數重新命名
// 例子 14-8 let { foo: baz } = { foo: 'aaa', bar: 'bbb' }; console.log(baz); // "aaa" 複製程式碼
5. 僅獲取部分屬性
// 例子 14-9 function test(input) { return [left, right, top, bottom]; } const [left, __, top] = test(input); function test(input) { return { left, right, top, bottom }; } const { left, right } = test(input); 複製程式碼
15. 增強的物件字面量
// 例子 15-1 // bad const something = 'y' const x = { something: something } // good const something = 'y' const x = { something }; 複製程式碼
動態屬性
// 例子 15-2 const x = { ['a' + '_' + 'b']: 'z' } console.log(x.a_b); // z 複製程式碼
16. 陣列的拓展方法
1. keys
// 例子 16-1 var arr = ["a", , "c"]; var sparseKeys = Object.keys(arr); console.log(sparseKeys); // ['0', '2'] var denseKeys = [...arr.keys()]; console.log(denseKeys);// [0, 1, 2] 複製程式碼
2. entries
// 例子 16-2 var arr = ["a", "b", "c"]; var iterator = arr.entries(); for (let e of iterator) { console.log(e); } 複製程式碼
3. values
// 例子 16-3 let arr = ['w', 'y', 'k', 'o', 'p']; let eArr = arr.values(); for (let letter of eArr) { console.log(letter); } 複製程式碼
4. includes
// 例子 16-4 // bad function test(fruit) { if (fruit == 'apple' || fruit == 'strawberry') { console.log('red'); } } // good function test(fruit) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (redFruits.includes(fruit)) { console.log('red'); } } 複製程式碼
5. find
// 例子 16-5 var inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; function findCherries(fruit) { return fruit.name === 'cherries'; } console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 } 複製程式碼
6. findIndex
// 例子 16-6 function isPrime(element, index, array) { var start = 2; while (start <= Math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found console.log([4, 6, 7, 12].findIndex(isPrime)); // 2 複製程式碼
更多的就不列舉了。
17.optional-chaining
舉個例子:
// 例子 17-1 const obj = { foo: { bar: { baz: 42, }, }, }; const baz = obj?.foo?.bar?.baz; // 42 複製程式碼
同樣支援函式:
// 例子 17-2 function test() { return 42; } test?.(); // 42 exists?.(); // undefined 複製程式碼
需要新增@babel/plugin-proposal-optional-chaining 外掛支援
18. logical-assignment-operators
// 例子 18-1 a ||= b; obj.a.b ||= c; a &&= b; obj.a.b &&= c; 複製程式碼
Babel 編譯為:
var _obj$a, _obj$a2; a || (a = b); (_obj$a = obj.a).b || (_obj$a.b = c); a && (a = b); (_obj$a2 = obj.a).b && (_obj$a2.b = c); 複製程式碼
出現的原因:
// 例子 18-2 function example(a = b) { // a 必須是 undefined if (!a) { a = b; } } function numeric(a = b) { // a 必須是 null 或者 undefined if (a == null) { a = b; } } // a 可以是任何 falsy 的值 function example(a = b) { // 可以,但是一定會觸發 setter a = a || b; // 不會觸發 setter,但可能會導致 lint error a || (a = b); // 就有人提出了這種寫法: a ||= b; } 複製程式碼
需要@babel/plugin-proposal-logical-assignment-operators 外掛支援
19. nullish-coalescing-operator
a ?? b // 相當於 (a !== null && a !== void 0) ? a : b 複製程式碼
舉個例子:
var foo = object.foo ?? "default"; // 相當於 var foo = (object.foo != null) ? object.foo : "default"; 複製程式碼
需要@babel/plugin-proposal-nullish-coalescing-operator 外掛支援
20. pipeline-operator
const double = (n) => n * 2; const increment = (n) => n + 1; // 沒有用管道操作符 double(increment(double(5))); // 22 // 用上管道操作符之後 5 |> double |> increment |> double; // 22 複製程式碼
其他
新開了知乎專欄,大家可以在更多的平臺上看到我的文章,歡迎關注哦~
參考
- ES6 實踐規範
- babel 7 簡單升級指南
- 不得不知的 ES6 小技巧
- 深入解析 ES6:Symbol
- 什麼時候你不能使用箭頭函式?
- 一些使 JavaScript 更加簡潔的小技巧
- 幾分鐘內提升技能的 8 個 JavaScript 方法
- [譯] 如何使用 JavaScript ES6 有條件地構造物件
- 5 個技巧讓你更好的編寫 JavaScript(ES6) 中條件語句
- ES6 帶來的重大特性 – JavaScript 完全手冊(2018版)
ES6 系列
ES6 系列目錄地址:github.com/mqyqingfeng…
ES6 系列預計寫二十篇左右,旨在加深 ES6 部分知識點的理解,重點講解塊級作用域、標籤模板、箭頭函式、Symbol、Set、Map 以及 Promise 的模擬實現、模組載入方案、非同步處理等內容。
如果有錯誤或者不嚴謹的地方,請務必給予指正,十分感謝。如果喜歡或者有所啟發,歡迎 star,對作者也是一種鼓勵。