* [13.1](https://github.com/yuche/javascript#13.1)?一直使用?`const`?來聲明變量,如果不這樣做就會產生全局變量。我們需要避免全局命名空間的污染。[地球隊長](http://www.wikiwand.com/en/Captain_Planet)已經警告過我們了。(譯注:全局,global 亦有全球的意思。地球隊長的責任是保衛地球環境,所以他警告我們不要造成「全球」污染。)
~~~
// bad
superPower = new SuperPower();
// good
const superPower = new SuperPower();
~~~
* [13.2](https://github.com/yuche/javascript#13.2)?使用?`var`?聲明每一個變量。
> 為什么?增加新變量將變的更加容易,而且你永遠不用再擔心調換錯?`;`?跟?`,`。
~~~
// bad
const items = getItems(),
goSportsTeam = true,
dragonball = 'z';
// bad
// (compare to above, and try to spot the mistake)
const items = getItems(),
goSportsTeam = true;
dragonball = 'z';
// good
const items = getItems();
const goSportsTeam = true;
const dragonball = 'z';
~~~
* [13.3](https://github.com/yuche/javascript#13.3)?將所有的?`const`?和?`let`?分組
> 為什么?當你需要把已賦值變量賦值給未賦值變量時非常有用。
~~~
// bad
let i, len, dragonball,
items = getItems(),
goSportsTeam = true;
// bad
let i;
const items = getItems();
let dragonball;
const goSportsTeam = true;
let len;
// good
const goSportsTeam = true;
const items = getItems();
let dragonball;
let i;
let length;
~~~
* [13.4](https://github.com/yuche/javascript#13.4)?在你需要的地方給變量賦值,但請把它們放在一個合理的位置。
> 為什么?`let`?和?`const`?是塊級作用域而不是函數作用域。
~~~
// good
function() {
test();
console.log('doing stuff..');
//..other stuff..
const name = getName();
if (name === 'test') {
return false;
}
return name;
}
// bad - unnecessary function call
function(hasName) {
const name = getName();
if (!hasName) {
return false;
}
this.setFirstName(name);
return true;
}
// good
function(hasName) {
if (!hasName) {
return false;
}
const name = getName();
this.setFirstName(name);
return true;
}
~~~
- 關于
- 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