* [3.1](https://github.com/yuche/javascript#3.1)?使用字面值創建對象。
~~~
// bad
const item = new Object();
// good
const item = {};
~~~
* [3.2](https://github.com/yuche/javascript#3.2)?如果你的代碼在瀏覽器環境下執行,別使用?[保留字](http://es5.github.io/#x7.6.1)?作為鍵值。這樣的話在 IE8 不會運行。?[更多信息](https://github.com/airbnb/javascript/issues/61)。 但在 ES6 模塊和服務器端中使用沒有問題。
~~~
// bad
const superman = {
default: { clark: 'kent' },
private: true,
};
// good
const superman = {
defaults: { clark: 'kent' },
hidden: true,
};
~~~
* [3.3](https://github.com/yuche/javascript#3.3)?使用同義詞替換需要使用的保留字。
~~~
// bad
const superman = {
class: 'alien',
};
// bad
const superman = {
klass: 'alien',
};
// good
const superman = {
type: 'alien',
};
~~~
* [3.4](https://github.com/yuche/javascript#3.4)?創建有動態屬性名的對象時,使用可被計算的屬性名稱。
> 為什么?因為這樣可以讓你在一個地方定義所有的對象屬性。
~~~
function getKey(k) {
return `a key named ${k}`;
}
// bad
const obj = {
id: 5,
name: 'San Francisco',
};
obj[getKey('enabled')] = true;
// good
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};
~~~
* [3.5](https://github.com/yuche/javascript#3.5)?使用對象方法的簡寫。
~~~
// bad
const atom = {
value: 1,
addValue: function (value) {
return atom.value + value;
},
};
// good
const atom = {
value: 1,
addValue(value) {
return atom.value + value;
},
};
~~~
* [3.6](https://github.com/yuche/javascript#3.6)?使用對象屬性值的簡寫。
> 為什么?因為這樣更短更有描述性。
~~~
const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
lukeSkywalker: lukeSkywalker,
};
// good
const obj = {
lukeSkywalker,
};
~~~
* [3.7](https://github.com/yuche/javascript#3.7)?在對象屬性聲明前把簡寫的屬性分組。
> 為什么?因為這樣能清楚地看出哪些屬性使用了簡寫。
~~~
const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
episodeOne: 1,
twoJedisWalkIntoACantina: 2,
lukeSkywalker,
episodeThree: 3,
mayTheFourth: 4,
anakinSkywalker,
};
// good
const obj = {
lukeSkywalker,
anakinSkywalker,
episodeOne: 1,
twoJedisWalkIntoACantina: 2,
episodeThree: 3,
mayTheFourth: 4,
};
~~~
- 關于
- 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