* 立即執行函數可以寫成箭頭函數的形式。
```
(() => {
console.log('Welcome to the Internet.');
})();
```
* 那些需要使用函數表達式的場合,盡量用箭頭函數代替。因為這樣更簡潔,而且綁定了 this。
```
// bad
[1, 2, 3].map(function (x) {
return x * x;
});
// good
[1, 2, 3].map((x) => {
return x * x;
});
// best
[1, 2, 3].map(x => x * x);
```
* 箭頭函數取代Function.prototype.bind,不應再用 self/_this/that 綁定 this。
```
// bad
const self = this;
const boundMethod = function(...params) {
return method.apply(self, params);
}
// acceptable
const boundMethod = method.bind(this);
// best
const boundMethod = (...params) => method.apply(this, params);
```
* 簡單的、單行的、不會復用的函數,建議采用箭頭函數。如果函數體較為復雜,行數較多,還是應該采用傳統的函數寫法。
* 所有配置項都應該集中在一個對象,放在最后一個參數,布爾值不可以直接作為參數。
```
// bad
function divide(a, b, option = false ) {
}
// good
function divide(a, b, { option = false } = {}) {
}
```
* 使用默認值語法設置函數參數的默認值。
```
// bad
function handleThings(opts) {
opts = opts || {};
}
// good
function handleThings(opts = {}) {
// ...
}
```