* [7.1](https://github.com/yuche/javascript#7.1)?使用函數聲明代替函數表達式。
> 為什么?因為函數聲明是可命名的,所以他們在調用棧中更容易被識別。此外,函數聲明會把整個函數提升(hoisted),而函數表達式只會把函數的引用變量名提升。這條規則使得[箭頭函數](https://github.com/yuche/javascript#arrow-functions)可以取代函數表達式。
~~~
// bad
const foo = function () {
};
// good
function foo() {
}
~~~
* [7.2](https://github.com/yuche/javascript#7.2)?函數表達式:
~~~
// 立即調用的函數表達式 (IIFE)
(() => {
console.log('Welcome to the Internet. Please follow me.');
})();
~~~
* [7.3](https://github.com/yuche/javascript#7.3)?永遠不要在一個非函數代碼塊(`if`、`while`?等)中聲明一個函數,把那個函數賦給一個變量。瀏覽器允許你這么做,但它們的解析表現不一致。
* [7.4](https://github.com/yuche/javascript#7.4)?**注意:**?ECMA-262 把?`block`?定義為一組語句。函數聲明不是語句。[閱讀 ECMA-262 關于這個問題的說明](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf#page=97)。
~~~
// bad
if (currentUser) {
function test() {
console.log('Nope.');
}
}
// good
let test;
if (currentUser) {
test = () => {
console.log('Yup.');
};
}
~~~
* [7.5](https://github.com/yuche/javascript#7.5)?永遠不要把參數命名為?`arguments`。這將取代原來函數作用域內的?`arguments`?對象。
~~~
// bad
function nope(name, options, arguments) {
// ...stuff...
}
// good
function yup(name, options, args) {
// ...stuff...
}
~~~
* [7.6](https://github.com/yuche/javascript#7.6)?不要使用?`arguments`。可以選擇 rest 語法?`...`?替代。
> 為什么?使用?`...`?能明確你要傳入的參數。另外 rest 參數是一個真正的數組,而?`arguments`是一個類數組。
~~~
// bad
function concatenateAll() {
const args = Array.prototype.slice.call(arguments);
return args.join('');
}
// good
function concatenateAll(...args) {
return args.join('');
}
~~~
* [7.7](https://github.com/yuche/javascript#7.7)?直接給函數的參數指定默認值,不要使用一個變化的函數參數。
~~~
// really bad
function handleThings(opts) {
// 不!我們不應該改變函數參數。
// 更加糟糕: 如果參數 opts 是 false 的話,它就會被設定為一個對象。
// 但這樣的寫法會造成一些 Bugs。
//(譯注:例如當 opts 被賦值為空字符串,opts 仍然會被下一行代碼設定為一個空對象。)
opts = opts || {};
// ...
}
// still bad
function handleThings(opts) {
if (opts === void 0) {
opts = {};
}
// ...
}
// good
function handleThings(opts = {}) {
// ...
}
~~~
* [7.8](https://github.com/yuche/javascript#7.8)?直接給函數參數賦值時需要避免副作用。
> 為什么?因為這樣的寫法讓人感到很困惑。
~~~
var b = 1;
// bad
function count(a = b++) {
console.log(a);
}
count(); // 1
count(); // 2
count(3); // 3
count(); // 3
~~~
- 關于
- 1. 類型
- 2. 引用
- 3. 對象
- 4. 數組
- 5. 解構
- 6. 字符串
- 7. 函數
- 8. 箭頭函數
- 9. 構造函數
- 10. 模塊
- 11. Iterators & Generators
- 12. 屬性
- 13. 變量
- 14. 提升
- 15. 比較運算符 & 等號
- 16. 代碼塊
- 17. 注釋
- 18. 空白
- 19. 逗號
- 20. 分號
- 21. 類型轉換
- 22. 命名規則
- 23. 存取器
- 24. 事件
- 25. jQuery
- 26. ECMAScript 5 兼容性
- 27. ECMAScript 6 編碼規范
- 28. 測試
- 29. 性能
- 30. 資源
- 31. 使用人群
- 32. 翻譯
- 33. JavaScript 編碼規范說明
- 34. 一起來討論Javascript
- 35. Contributors
- 36. License