es6 规范指南

用更合理的方式写 JavaScript

类型

  • 1.1 基本类型: 直接存取基本类型。

    • 字符串
    • 数值
    • 布尔类型
    • null
    • undefined
    1. const foo = 1;
    2. let bar = foo;
    3. bar = 9;
    4. console.log(foo, bar); // => 1, 9
  • 1.2 复制类型: 通过引用的方式存取复杂类型。

    • 对象
    • 数组
    • 函数
    1. const foo = [1, 2];
    2. const bar = foo;
    3. bar[0] = 9;
    4. console.log(foo[0], bar[0]); // => 9, 9

⬆ 返回目录

引用

  • 2.1 对所有的引用使用 const ;不要使用 var

    为什么?这能确保你无法对引用重新赋值,也不会导致出现 bug 或难以理解。

    1. // bad
    2. var a = 1;
    3. var b = 2;
    4. // good
    5. const a = 1;
    6. const b = 2;
  • 2.2 如果你一定需要可变动的引用,使用 let 代替 var

    为什么?因为 let 是块级作用域,而 var 是函数作用域。

    1. // bad
    2. var count = 1;
    3. if (true) {
    4. count += 1;
    5. }
    6. // good, use the let.
    7. let count = 1;
    8. if (true) {
    9. count += 1;
    10. }
  • 2.3 注意 letconst 都是块级作用域。

    1. // const 和 let 只存在于它们被定义的区块内。
    2. {
    3. let a = 1;
    4. const b = 1;
    5. }
    6. console.log(a); // ReferenceError
    7. console.log(b); // ReferenceError

⬆ 返回目录

对象

  • 3.1 使用字面值创建对象。

    1. // bad
    2. const item = new Object();
    3. // good
    4. const item = {};
  • 3.2 如果你的代码在浏览器环境下执行,别使用 保留字 作为键值。这样的话在 IE8 不会运行。 更多信息。 但在 ES6 模块和服务器端中使用没有问题。

    1. // bad
    2. const superman = {
    3. default: { clark: 'kent' },
    4. private: true,
    5. };
    6. // good
    7. const superman = {
    8. defaults: { clark: 'kent' },
    9. hidden: true,
    10. };
  • 3.3 使用同义词替换需要使用的保留字。

    1. // bad
    2. const superman = {
    3. class: 'alien',
    4. };
    5. // bad
    6. const superman = {
    7. klass: 'alien',
    8. };
    9. // good
    10. const superman = {
    11. type: 'alien',
    12. };

  • 3.4 创建有动态属性名的对象时,使用可被计算的属性名称。

    为什么?因为这样可以让你在一个地方定义所有的对象属性。

    ``javascript function getKey(k) { returna key named ${k}`; }

    // bad const obj = { id: 5, name: ‘San Francisco’, }; obj[getKey(‘enabled’)] = true;

    // good const obj = { id: 5, name: ‘San Francisco’,

  1. [getKey('enabled')]: true,
  2. };
  3. ```

  • 3.5 使用对象方法的简写。

    1. // bad
    2. const atom = {
    3. value: 1,
    4. addValue: function (value) {
    5. return atom.value + value;
    6. },
    7. };
    8. // good
    9. const atom = {
    10. value: 1,
    11. addValue(value) {
    12. return atom.value + value;
    13. },
    14. };

  • 3.6 使用对象属性值的简写。

    为什么?因为这样更短更有描述性。

    1. const lukeSkywalker = 'Luke Skywalker';
    2. // bad
    3. const obj = {
    4. lukeSkywalker: lukeSkywalker,
    5. };
    6. // good
    7. const obj = {
    8. lukeSkywalker,
    9. };
  • 3.7 在对象属性声明前把简写的属性分组。

    为什么?因为这样能清楚地看出哪些属性使用了简写。

    1. const anakinSkywalker = 'Anakin Skywalker';
    2. const lukeSkywalker = 'Luke Skywalker';
    3. // bad
    4. const obj = {
    5. episodeOne: 1,
    6. twoJedisWalkIntoACantina: 2,
    7. lukeSkywalker,
    8. episodeThree: 3,
    9. mayTheFourth: 4,
    10. anakinSkywalker,
    11. };
    12. // good
    13. const obj = {
    14. lukeSkywalker,
    15. anakinSkywalker,
    16. episodeOne: 1,
    17. twoJedisWalkIntoACantina: 2,
    18. episodeThree: 3,
    19. mayTheFourth: 4,
    20. };

⬆ 返回目录

数组

  • 4.1 使用字面值创建数组。

    1. // bad
    2. const items = new Array();
    3. // good
    4. const items = [];
  • 4.2 向数组添加元素时使用 Arrary#push 替代直接赋值。

    ```javascript const someStack = [];

  1. // bad
  2. someStack[someStack.length] = 'abracadabra';
  3. // good
  4. someStack.push('abracadabra');
  5. ```

  • 4.3 使用拓展运算符 ... 复制数组。

    1. // bad
    2. const len = items.length;
    3. const itemsCopy = [];
    4. let i;
    5. for (i = 0; i < len; i++) {
    6. itemsCopy[i] = items[i];
    7. }
    8. // good
    9. const itemsCopy = [...items];
  • 4.4 使用 Array#from 把一个类数组对象转换成数组。

    1. const foo = document.querySelectorAll('.foo');
    2. const nodes = Array.from(foo);

⬆ 返回目录

解构

  • 5.1 使用解构存取和使用多属性对象。

    为什么?因为解构能减少临时引用属性。

    1. // bad
    2. function getFullName(user) {
    3. const firstName = user.firstName;
    4. const lastName = user.lastName;
    5. return `${firstName} ${lastName}`;
    6. }
    7. // good
    8. function getFullName(obj) {
    9. const { firstName, lastName } = obj;
    10. return `${firstName} ${lastName}`;
    11. }
    12. // best
    13. function getFullName({ firstName, lastName }) {
    14. return `${firstName} ${lastName}`;
    15. }
  • 5.2 对数组使用解构赋值。

    1. const arr = [1, 2, 3, 4];
    2. // bad
    3. const first = arr[0];
    4. const second = arr[1];
    5. // good
    6. const [first, second] = arr;
  • 5.3 需要回传多个值时,使用对象解构,而不是数组解构。

    为什么?增加属性或者改变排序不会改变调用时的位置。

    1. // bad
    2. function processInput(input) {
    3. // then a miracle occurs
    4. return [left, right, top, bottom];
    5. }
    6. // 调用时需要考虑回调数据的顺序。
    7. const [left, __, top] = processInput(input);
    8. // good
    9. function processInput(input) {
    10. // then a miracle occurs
    11. return { left, right, top, bottom };
    12. }
    13. // 调用时只选择需要的数据
    14. const { left, right } = processInput(input);

⬆ 返回目录

Strings

  • 6.1 字符串使用单引号 ''

    1. // bad
    2. const name = "Capt. Janeway";
    3. // good
    4. const name = 'Capt. Janeway';
  • 6.2 字符串超过 80 个字节应该使用字符串连接号换行。

  • 6.3 注:过度使用字串连接符号可能会对性能造成影响。jsPerf讨论.

    1. // bad
    2. const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
    3. // bad
    4. const errorMessage = 'This is a super long error that was thrown because \
    5. of Batman. When you stop to think about how Batman had anything to do \
    6. with this, you would get nowhere \
    7. fast.';
    8. // good
    9. const errorMessage = 'This is a super long error that was thrown because ' +
    10. 'of Batman. When you stop to think about how Batman had anything to do ' +
    11. 'with this, you would get nowhere fast.';

  • 6.4 程序化生成字符串时,使用模板字符串代替字符串连接。

    为什么?模板字符串更为简洁,更具可读性。

    1. // bad
    2. function sayHi(name) {
    3. return 'How are you, ' + name + '?';
    4. }
    5. // bad
    6. function sayHi(name) {
    7. return ['How are you, ', name, '?'].join();
    8. }
    9. // good
    10. function sayHi(name) {
    11. return `How are you, ${name}?`;
    12. }

⬆ 返回目录

函数

  • 7.1 使用函数声明代替函数表达式。

    为什么?因为函数声明是可命名的,所以他们在调用栈中更容易被识别。此外,函数声明会把整个函数提升(hoisted),而函数表达式只会把函数的引用变量名提升。这条规则使得箭头函数可以取代函数表达式。

    1. // bad
    2. const foo = function () {
    3. };
    4. // good
    5. function foo() {
    6. }
  • 7.2 函数表达式:

    1. // 立即调用的函数表达式 (IIFE)
    2. (() => {
    3. console.log('Welcome to the Internet. Please follow me.');
    4. })();
  • 7.3 永远不要在一个非函数代码块(ifwhile 等)中声明一个函数,把那个函数赋给一个变量。浏览器允许你这么做,但它们的解析表现不一致。

  • 7.4 注意: ECMA-262 把 block 定义为一组语句。函数声明不是语句。阅读 ECMA-262 关于这个问题的说明

    1. // bad
    2. if (currentUser) {
    3. function test() {
    4. console.log('Nope.');
    5. }
    6. }
    7. // good
    8. let test;
    9. if (currentUser) {
    10. test = () => {
    11. console.log('Yup.');
    12. };
    13. }
  • 7.5 永远不要把参数命名为 arguments。这将取代原来函数作用域内的 arguments 对象。

    1. // bad
    2. function nope(name, options, arguments) {
    3. // ...stuff...
    4. }
    5. // good
    6. function yup(name, options, args) {
    7. // ...stuff...
    8. }

  • 7.6 不要使用 arguments。可以选择 rest 语法 ... 替代。

    为什么?使用 ... 能明确你要传入的参数。另外 rest 参数是一个真正的数组,而 arguments 是一个类数组。

    1. // bad
    2. function concatenateAll() {
    3. const args = Array.prototype.slice.call(arguments);
    4. return args.join('');
    5. }
    6. // good
    7. function concatenateAll(...args) {
    8. return args.join('');
    9. }

  • 7.7 直接给函数的参数指定默认值,不要使用一个变化的函数参数。

    1. // really bad
    2. function handleThings(opts) {
    3. // 不!我们不应该改变函数参数。
    4. // 更加糟糕: 如果参数 opts 是 false 的话,它就会被设定为一个对象。
    5. // 但这样的写法会造成一些 Bugs。
    6. //(译注:例如当 opts 被赋值为空字符串,opts 仍然会被下一行代码设定为一个空对象。)
    7. opts = opts || {};
    8. // ...
    9. }
    10. // still bad
    11. function handleThings(opts) {
    12. if (opts === void 0) {
    13. opts = {};
    14. }
    15. // ...
    16. }
    17. // good
    18. function handleThings(opts = {}) {
    19. // ...
    20. }
  • 7.8 直接给函数参数赋值时需要避免副作用。

    为什么?因为这样的写法让人感到很困惑。

    1. var b = 1;
    2. // bad
    3. function count(a = b++) {
    4. console.log(a);
    5. }
    6. count(); // 1
    7. count(); // 2
    8. count(3); // 3
    9. count(); // 3

⬆ 返回目录

箭头函数

  • 8.1 当你必须使用函数表达式(或传递一个匿名函数)时,使用箭头函数符号。

    为什么?因为箭头函数创造了新的一个 this 执行环境(译注:参考 Arrow functions - JavaScript | MDNES6 arrow functions, syntax and lexical scoping),通常情况下都能满足你的需求,而且这样的写法更为简洁。

    为什么不?如果你有一个相当复杂的函数,你或许可以把逻辑部分转移到一个函数声明上。

    1. // bad
    2. [1, 2, 3].map(function (x) {
    3. return x * x;
    4. });
    5. // good
    6. [1, 2, 3].map((x) => {
    7. return x * x;
    8. });
  • 8.2 如果一个函数适合用一行写出并且只有一个参数,那就把花括号、圆括号和 return 都省略掉。如果不是,那就不要省略。

    为什么?语法糖。在链式调用中可读性很高。

    为什么不?当你打算回传一个对象的时候。

    1. // good
    2. [1, 2, 3].map(x => x * x);
    3. // good
    4. [1, 2, 3].reduce((total, n) => {
    5. return total + n;
    6. }, 0);

⬆ 返回目录

构造器

  • 9.1 总是使用 class。避免直接操作 prototype

    为什么? 因为 class 语法更为简洁更易读。

    ```javascript // bad function Queue(contents = []) { this._queue = […contents]; } Queue.prototype.pop = function() { const value = this._queue[0]; this._queue.splice(0, 1); return value; }

  1. // good
  2. class Queue {
  3. constructor(contents = []) {
  4. this._queue = [...contents];
  5. }
  6. pop() {
  7. const value = this._queue[0];
  8. this._queue.splice(0, 1);
  9. return value;
  10. }
  11. }
  12. ```
  • 9.2 使用 extends 继承。

    为什么?因为 extends 是一个内建的原型继承方法并且不会破坏 instanceof

    1. // bad
    2. const inherits = require('inherits');
    3. function PeekableQueue(contents) {
    4. Queue.apply(this, contents);
    5. }
    6. inherits(PeekableQueue, Queue);
    7. PeekableQueue.prototype.peek = function() {
    8. return this._queue[0];
    9. }
    10. // good
    11. class PeekableQueue extends Queue {
    12. peek() {
    13. return this._queue[0];
    14. }
    15. }
  • 9.3 方法可以返回 this 来帮助链式调用。

    1. // bad
    2. Jedi.prototype.jump = function() {
    3. this.jumping = true;
    4. return true;
    5. };
    6. Jedi.prototype.setHeight = function(height) {
    7. this.height = height;
    8. };
    9. const luke = new Jedi();
    10. luke.jump(); // => true
    11. luke.setHeight(20); // => undefined
    12. // good
    13. class Jedi {
    14. jump() {
    15. this.jumping = true;
    16. return this;
    17. }
    18. setHeight(height) {
    19. this.height = height;
    20. return this;
    21. }
    22. }
    23. const luke = new Jedi();
    24. luke.jump()
    25. .setHeight(20);
  • 9.4 可以写一个自定义的 toString() 方法,但要确保它能正常运行并且不会引起副作用。

    1. class Jedi {
    2. constructor(options = {}) {
    3. this.name = options.name || 'no name';
    4. }
    5. getName() {
    6. return this.name;
    7. }
    8. toString() {
    9. return `Jedi - ${this.getName()}`;
    10. }
    11. }

⬆ 返回目录

模块

  • 10.1 总是使用模组 (import/export) 而不是其他非标准模块系统。你可以编译为你喜欢的模块系统。

    为什么?模块就是未来,让我们开始迈向未来吧。

    1. // bad
    2. const AirbnbStyleGuide = require('./AirbnbStyleGuide');
    3. module.exports = AirbnbStyleGuide.es6;
    4. // ok
    5. import AirbnbStyleGuide from './AirbnbStyleGuide';
    6. export default AirbnbStyleGuide.es6;
    7. // best
    8. import { es6 } from './AirbnbStyleGuide';
    9. export default es6;
  • 10.2 不要使用通配符 import。

    为什么?这样能确保你只有一个默认 export。

    1. // bad
    2. import * as AirbnbStyleGuide from './AirbnbStyleGuide';
    3. // good
    4. import AirbnbStyleGuide from './AirbnbStyleGuide';
  • 10.3 不要从 import 中直接 export。

    为什么?虽然一行代码简洁明了,但让 import 和 export 各司其职让事情能保持一致。

    1. // bad
    2. // filename es6.js
    3. export { es6 as default } from './airbnbStyleGuide';
    4. // good
    5. // filename es6.js
    6. import { es6 } from './AirbnbStyleGuide';
    7. export default es6;

⬆ 返回目录

Iterators and Generators

  • 11.1 不要使用 iterators。使用高阶函数例如 map()reduce() 替代 for-of

    为什么?这加强了我们不变的规则。处理纯函数的回调值更易读,这比它带来的副作用更重要。

    1. const numbers = [1, 2, 3, 4, 5];
    2. // bad
    3. let sum = 0;
    4. for (let num of numbers) {
    5. sum += num;
    6. }
    7. sum === 15;
    8. // good
    9. let sum = 0;
    10. numbers.forEach((num) => sum += num);
    11. sum === 15;
    12. // best (use the functional force)
    13. const sum = numbers.reduce((total, num) => total + num, 0);
    14. sum === 15;
  • 11.2 现在还不要使用 generators。

    为什么?因为它们现在还没法很好地编译到 ES5。 (译者注:目前(2016/03) Chrome 和 Node.js 的稳定版本都已支持 generators)

⬆ 返回目录

属性

  • 12.1 使用 . 来访问对象的属性。

    1. const luke = {
    2. jedi: true,
    3. age: 28,
    4. };
    5. // bad
    6. const isJedi = luke['jedi'];
    7. // good
    8. const isJedi = luke.jedi;
  • 12.2 当通过变量访问属性时使用中括号 []

    1. const luke = {
    2. jedi: true,
    3. age: 28,
    4. };
    5. function getProp(prop) {
    6. return luke[prop];
    7. }
    8. const isJedi = getProp('jedi');

⬆ 返回目录

变量

  • 13.1 一直使用 const 来声明变量,如果不这样做就会产生全局变量。我们需要避免全局命名空间的污染。地球队长已经警告过我们了。(译注:全局,global 亦有全球的意思。地球队长的责任是保卫地球环境,所以他警告我们不要造成「全球」污染。)

    1. // bad
    2. superPower = new SuperPower();
    3. // good
    4. const superPower = new SuperPower();
  • 13.2 使用 const 声明每一个变量。

    为什么?增加新变量将变的更加容易,而且你永远不用再担心调换错 ;,

    1. // bad
    2. const items = getItems(),
    3. goSportsTeam = true,
    4. dragonball = 'z';
    5. // bad
    6. // (compare to above, and try to spot the mistake)
    7. const items = getItems(),
    8. goSportsTeam = true;
    9. dragonball = 'z';
    10. // good
    11. const items = getItems();
    12. const goSportsTeam = true;
    13. const dragonball = 'z';
  • 13.3 将所有的 constlet 分组

    为什么?当你需要把已赋值变量赋值给未赋值变量时非常有用。

    1. // bad
    2. let i, len, dragonball,
    3. items = getItems(),
    4. goSportsTeam = true;
    5. // bad
    6. let i;
    7. const items = getItems();
    8. let dragonball;
    9. const goSportsTeam = true;
    10. let len;
    11. // good
    12. const goSportsTeam = true;
    13. const items = getItems();
    14. let dragonball;
    15. let i;
    16. let length;
  • 13.4 在你需要的地方给变量赋值,但请把它们放在一个合理的位置。

    为什么?letconst 是块级作用域而不是函数作用域。

    1. // good
    2. function() {
    3. test();
    4. console.log('doing stuff..');
    5. //..other stuff..
    6. const name = getName();
    7. if (name === 'test') {
    8. return false;
    9. }
    10. return name;
    11. }
    12. // bad - unnecessary function call
    13. function(hasName) {
    14. const name = getName();
    15. if (!hasName) {
    16. return false;
    17. }
    18. this.setFirstName(name);
    19. return true;
    20. }
    21. // good
    22. function(hasName) {
    23. if (!hasName) {
    24. return false;
    25. }
    26. const name = getName();
    27. this.setFirstName(name);
    28. return true;
    29. }

⬆ 返回目录

Hoisting

  • 14.1 var 声明会被提升至该作用域的顶部,但它们赋值不会提升。letconst 被赋予了一种称为「暂时性死区(Temporal Dead Zones, TDZ)」的概念。这对于了解为什么 type of 不再安全相当重要。

    1. // 我们知道这样运行不了
    2. // (假设 notDefined 不是全局变量)
    3. function example() {
    4. console.log(notDefined); // => throws a ReferenceError
    5. }
    6. // 由于变量提升的原因,
    7. // 在引用变量后再声明变量是可以运行的。
    8. // 注:变量的赋值 `true` 不会被提升。
    9. function example() {
    10. console.log(declaredButNotAssigned); // => undefined
    11. var declaredButNotAssigned = true;
    12. }
    13. // 编译器会把函数声明提升到作用域的顶层,
    14. // 这意味着我们的例子可以改写成这样:
    15. function example() {
    16. let declaredButNotAssigned;
    17. console.log(declaredButNotAssigned); // => undefined
    18. declaredButNotAssigned = true;
    19. }
    20. // 使用 const 和 let
    21. function example() {
    22. console.log(declaredButNotAssigned); // => throws a ReferenceError
    23. console.log(typeof declaredButNotAssigned); // => throws a ReferenceError
    24. const declaredButNotAssigned = true;
    25. }
  • 14.2 匿名函数表达式的变量名会被提升,但函数内容并不会。

    1. function example() {
    2. console.log(anonymous); // => undefined
    3. anonymous(); // => TypeError anonymous is not a function
    4. var anonymous = function() {
    5. console.log('anonymous function expression');
    6. };
    7. }
  • 14.3 命名的函数表达式的变量名会被提升,但函数名和函数函数内容并不会。

    1. function example() {
    2. console.log(named); // => undefined
    3. named(); // => TypeError named is not a function
    4. superPower(); // => ReferenceError superPower is not defined
    5. var named = function superPower() {
    6. console.log('Flying');
    7. };
    8. }
    9. // the same is true when the function name
    10. // is the same as the variable name.
    11. function example() {
    12. console.log(named); // => undefined
    13. named(); // => TypeError named is not a function
    14. var named = function named() {
    15. console.log('named');
    16. }
    17. }
  • 14.4 函数声明的名称和函数体都会被提升。

    1. function example() {
    2. superPower(); // => Flying
    3. function superPower() {
    4. console.log('Flying');
    5. }
    6. }
  • 想了解更多信息,参考 Ben CherryJavaScript Scoping & Hoisting

⬆ 返回目录

比较运算符 & 等号

  • 15.1 优先使用 ===!== 而不是 ==!=.
  • 15.2 条件表达式例如 if 语句通过抽象方法 ToBoolean 强制计算它们的表达式并且总是遵守下面的规则:

    • 对象 被计算为 true
    • Undefined 被计算为 false
    • Null 被计算为 false
    • 布尔值 被计算为 布尔的值
    • 数字 如果是 +0、-0、或 NaN 被计算为 false, 否则为 true
    • 字符串 如果是空字符串 '' 被计算为 false,否则为 true
    1. if ([0]) {
    2. // true
    3. // An array is an object, objects evaluate to true
    4. }
  • 15.3 使用简写。

    1. // bad
    2. if (name !== '') {
    3. // ...stuff...
    4. }
    5. // good
    6. if (name) {
    7. // ...stuff...
    8. }
    9. // bad
    10. if (collection.length > 0) {
    11. // ...stuff...
    12. }
    13. // good
    14. if (collection.length) {
    15. // ...stuff...
    16. }
  • 15.4 想了解更多信息,参考 Angus Croll 的 Truth Equality and JavaScript

⬆ 返回目录

代码块

  • 16.1 使用大括号包裹所有的多行代码块。

    1. // bad
    2. if (test)
    3. return false;
    4. // good
    5. if (test) return false;
    6. // good
    7. if (test) {
    8. return false;
    9. }
    10. // bad
    11. function() { return false; }
    12. // good
    13. function() {
    14. return false;
    15. }
  • 16.2 如果通过 ifelse 使用多行代码块,把 else 放在 if 代码块关闭括号的同一行。

    1. // bad
    2. if (test) {
    3. thing1();
    4. thing2();
    5. }
    6. else {
    7. thing3();
    8. }
    9. // good
    10. if (test) {
    11. thing1();
    12. thing2();
    13. } else {
    14. thing3();
    15. }

⬆ 返回目录

注释

  • 17.1 使用 /** ... */ 作为多行注释。包含描述、指定所有参数和返回值的类型和值。

    1. // bad
    2. // make() returns a new element
    3. // based on the passed in tag name
    4. //
    5. // @param {String} tag
    6. // @return {Element} element
    7. function make(tag) {
    8. // ...stuff...
    9. return element;
    10. }
    11. // good
    12. /**
    13. * make() returns a new element
    14. * based on the passed in tag name
    15. *
    16. * @param {String} tag
    17. * @return {Element} element
    18. */
    19. function make(tag) {
    20. // ...stuff...
    21. return element;
    22. }
  • 17.2 使用 // 作为单行注释。在评论对象上面另起一行使用单行注释。在注释前插入空行。

    1. // bad
    2. const active = true; // is current tab
    3. // good
    4. // is current tab
    5. const active = true;
    6. // bad
    7. function getType() {
    8. console.log('fetching type...');
    9. // set the default type to 'no type'
    10. const type = this._type || 'no type';
    11. return type;
    12. }
    13. // good
    14. function getType() {
    15. console.log('fetching type...');
    16. // set the default type to 'no type'
    17. const type = this._type || 'no type';
    18. return type;
    19. }
  • 17.3 给注释增加 FIXMETODO 的前缀可以帮助其他开发者快速了解这是一个需要复查的问题,或是给需要实现的功能提供一个解决方式。这将有别于常见的注释,因为它们是可操作的。使用 FIXME -- need to figure this out 或者 TODO -- need to implement

  • 17.4 使用 // FIXME: 标注问题。

    1. class Calculator {
    2. constructor() {
    3. // FIXME: shouldn't use a global here
    4. total = 0;
    5. }
    6. }
  • 17.5 使用 // TODO: 标注问题的解决方式。

    1. class Calculator {
    2. constructor() {
    3. // TODO: total should be configurable by an options param
    4. this.total = 0;
    5. }
    6. }

⬆ 返回目录

空白

  • 18.1 使用 2 个空格作为缩进。

    1. // bad
    2. function() {
    3. ∙∙∙∙const name;
    4. }
    5. // bad
    6. function() {
    7. const name;
    8. }
    9. // good
    10. function() {
    11. ∙∙const name;
    12. }
  • 18.2 在花括号前放一个空格。

    1. // bad
    2. function test(){
    3. console.log('test');
    4. }
    5. // good
    6. function test() {
    7. console.log('test');
    8. }
    9. // bad
    10. dog.set('attr',{
    11. age: '1 year',
    12. breed: 'Bernese Mountain Dog',
    13. });
    14. // good
    15. dog.set('attr', {
    16. age: '1 year',
    17. breed: 'Bernese Mountain Dog',
    18. });
  • 18.3 在控制语句(ifwhile 等)的小括号前放一个空格。在函数调用及声明中,不在函数的参数列表前加空格。

    1. // bad
    2. if(isJedi) {
    3. fight ();
    4. }
    5. // good
    6. if (isJedi) {
    7. fight();
    8. }
    9. // bad
    10. function fight () {
    11. console.log ('Swooosh!');
    12. }
    13. // good
    14. function fight() {
    15. console.log('Swooosh!');
    16. }
  • 18.4 使用空格把运算符隔开。

    1. // bad
    2. const x=y+5;
    3. // good
    4. const x = y + 5;
  • 18.5 在文件末尾插入一个空行。

    1. // bad
    2. (function(global) {
    3. // ...stuff...
    4. })(this);
    1. // bad
    2. (function(global) {
    3. // ...stuff...
    4. })(this);↵
    1. // good
    2. (function(global) {
    3. // ...stuff...
    4. })(this);↵
  • 18.5 在使用长方法链时进行缩进。使用前面的点 . 强调这是方法调用而不是新语句。

    1. // bad
    2. $('#items').find('.selected').highlight().end().find('.open').updateCount();
    3. // bad
    4. $('#items').
    5. find('.selected').
    6. highlight().
    7. end().
    8. find('.open').
    9. updateCount();
    10. // good
    11. $('#items')
    12. .find('.selected')
    13. .highlight()
    14. .end()
    15. .find('.open')
    16. .updateCount();
    17. // bad
    18. const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').class('led', true)
    19. .attr('width', (radius + margin) * 2).append('svg:g')
    20. .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
    21. .call(tron.led);
    22. // good
    23. const leds = stage.selectAll('.led')
    24. .data(data)
    25. .enter().append('svg:svg')
    26. .classed('led', true)
    27. .attr('width', (radius + margin) * 2)
    28. .append('svg:g')
    29. .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
    30. .call(tron.led);
  • 18.6 在块末和新语句前插入空行。

    1. // bad
    2. if (foo) {
    3. return bar;
    4. }
    5. return baz;
    6. // good
    7. if (foo) {
    8. return bar;
    9. }
    10. return baz;
    11. // bad
    12. const obj = {
    13. foo() {
    14. },
    15. bar() {
    16. },
    17. };
    18. return obj;
    19. // good
    20. const obj = {
    21. foo() {
    22. },
    23. bar() {
    24. },
    25. };
    26. return obj;
  • 18.7 单行对象在 {} 内部前后各加一个空格

    1. // bad
    2. const {firstName, lastName} = obj;
    3. // good
    4. const { firstName, lastName } = obj;

⬆ 返回目录

逗号

  • 19.1 行首逗号:不需要

    1. // bad
    2. const story = [
    3. once
    4. , upon
    5. , aTime
    6. ];
    7. // good
    8. const story = [
    9. once,
    10. upon,
    11. aTime,
    12. ];
    13. // bad
    14. const hero = {
    15. firstName: 'Ada'
    16. , lastName: 'Lovelace'
    17. , birthYear: 1815
    18. , superPower: 'computers'
    19. };
    20. // good
    21. const hero = {
    22. firstName: 'Ada',
    23. lastName: 'Lovelace',
    24. birthYear: 1815,
    25. superPower: 'computers',
    26. };
  • 19.2 多行对象增加结尾的逗号: 需要。(单行定义的对象,最后一个成员不以逗号结尾)

    为什么? 这会让 git diffs 更干净。另外,像 babel 这样的转译器会移除结尾多余的逗号,也就是说你不必担心老旧浏览器的尾逗号问题

    1. // bad - git diff without trailing comma
    2. const hero = {
    3. firstName: 'Florence',
    4. - lastName: 'Nightingale'
    5. + lastName: 'Nightingale',
    6. + inventorOf: ['coxcomb graph', 'modern nursing']
    7. }
    8. // good - git diff with trailing comma
    9. const hero = {
    10. firstName: 'Florence',
    11. lastName: 'Nightingale',
    12. + inventorOf: ['coxcomb chart', 'modern nursing'],
    13. }
    14. // bad
    15. const hero = {
    16. firstName: 'Dana',
    17. lastName: 'Scully'
    18. };
    19. const heroes = [
    20. 'Batman',
    21. 'Superman'
    22. ];
    23. // good
    24. const hero = {
    25. firstName: 'Dana',
    26. lastName: 'Scully',
    27. };
    28. const heroes = [
    29. 'Batman',
    30. 'Superman',
    31. ];

⬆ 返回目录

分号

  • 20.1 使用分号

    1. // bad
    2. (function() {
    3. const name = 'Skywalker'
    4. return name
    5. })()
    6. // good
    7. (() => {
    8. const name = 'Skywalker';
    9. return name;
    10. })();
    11. // good (防止函数在两个 IIFE 合并时被当成一个参数)
    12. ;(() => {
    13. const name = 'Skywalker';
    14. return name;
    15. })();

    Read more.

⬆ 返回目录

类型转换

  • 21.1 在语句开始时执行类型转换。
  • 21.2 字符串:

    1. // => this.reviewScore = 9;
    2. // bad
    3. const totalScore = this.reviewScore + '';
    4. // good
    5. const totalScore = String(this.reviewScore);
  • 21.3 对数字使用 parseInt 转换,并带上类型转换的基数。

    1. const inputValue = '4';
    2. // bad
    3. const val = new Number(inputValue);
    4. // bad
    5. const val = +inputValue;
    6. // bad
    7. const val = inputValue >> 0;
    8. // bad
    9. const val = parseInt(inputValue);
    10. // good
    11. const val = Number(inputValue);
    12. // good
    13. const val = parseInt(inputValue, 10);
  • 21.4 如果因为某些原因 parseInt 成为你所做的事的瓶颈而需要使用位操作解决性能问题时,留个注释说清楚原因和你的目的。

    1. // good
    2. /**
    3. * 使用 parseInt 导致我的程序变慢,
    4. * 改成使用位操作转换数字快多了。
    5. */
    6. const val = inputValue >> 0;
  • 21.5 注: 小心使用位操作运算符。数字会被当成 64 位值,但是位操作运算符总是返回 32 位的整数(参考)。位操作处理大于 32 位的整数值时还会导致意料之外的行为。关于这个问题的讨论。最大的 32 位整数是 2,147,483,647:

    1. 2147483647 >> 0 //=> 2147483647
    2. 2147483648 >> 0 //=> -2147483648
    3. 2147483649 >> 0 //=> -2147483647
  • 21.6 布尔:

    1. const age = 0;
    2. // bad
    3. const hasAge = new Boolean(age);
    4. // good
    5. const hasAge = Boolean(age);
    6. // good
    7. const hasAge = !!age;

⬆ 返回目录

命名规则

  • 22.1 避免单字母命名。命名应具备描述性。

    1. // bad
    2. function q() {
    3. // ...stuff...
    4. }
    5. // good
    6. function query() {
    7. // ..stuff..
    8. }
  • 22.2 使用驼峰式命名对象、函数和实例。

    1. // bad
    2. const OBJEcttsssss = {};
    3. const this_is_my_object = {};
    4. function c() {}
    5. // good
    6. const thisIsMyObject = {};
    7. function thisIsMyFunction() {}
  • 22.3 使用帕斯卡式命名构造函数或类。

    1. // bad
    2. function user(options) {
    3. this.name = options.name;
    4. }
    5. const bad = new user({
    6. name: 'nope',
    7. });
    8. // good
    9. class User {
    10. constructor(options) {
    11. this.name = options.name;
    12. }
    13. }
    14. const good = new User({
    15. name: 'yup',
    16. });
  • 22.4 使用下划线 _ 开头命名私有属性。

    1. // bad
    2. this.__firstName__ = 'Panda';
    3. this.firstName_ = 'Panda';
    4. // good
    5. this._firstName = 'Panda';
  • 22.5 别保存 this 的引用。使用箭头函数或 Function#bind。

    1. // bad
    2. function foo() {
    3. const self = this;
    4. return function() {
    5. console.log(self);
    6. };
    7. }
    8. // bad
    9. function foo() {
    10. const that = this;
    11. return function() {
    12. console.log(that);
    13. };
    14. }
    15. // good
    16. function foo() {
    17. return () => {
    18. console.log(this);
    19. };
    20. }
  • 22.6 如果你的文件只输出一个类,那你的文件名必须和类名完全保持一致。

    1. // file contents
    2. class CheckBox {
    3. // ...
    4. }
    5. export default CheckBox;
    6. // in some other file
    7. // bad
    8. import CheckBox from './checkBox';
    9. // bad
    10. import CheckBox from './check_box';
    11. // good
    12. import CheckBox from './CheckBox';
  • 22.7 当你导出默认的函数时使用驼峰式命名。你的文件名必须和函数名完全保持一致。

    1. function makeStyleGuide() {
    2. }
    3. export default makeStyleGuide;
  • 22.8 当你导出单例、函数库、空对象时使用帕斯卡式命名。

    1. const AirbnbStyleGuide = {
    2. es6: {
    3. }
    4. };
    5. export default AirbnbStyleGuide;

⬆ 返回目录

存取器

  • 23.1 属性的存取函数不是必须的。
  • 23.2 如果你需要存取函数时使用 getVal()setVal('hello')

    1. // bad
    2. dragon.age();
    3. // good
    4. dragon.getAge();
    5. // bad
    6. dragon.age(25);
    7. // good
    8. dragon.setAge(25);
  • 23.3 如果属性是布尔值,使用 isVal()hasVal()

    1. // bad
    2. if (!dragon.age()) {
    3. return false;
    4. }
    5. // good
    6. if (!dragon.hasAge()) {
    7. return false;
    8. }
  • 23.4 创建 get()set() 函数是可以的,但要保持一致。

    1. class Jedi {
    2. constructor(options = {}) {
    3. const lightsaber = options.lightsaber || 'blue';
    4. this.set('lightsaber', lightsaber);
    5. }
    6. set(key, val) {
    7. this[key] = val;
    8. }
    9. get(key) {
    10. return this[key];
    11. }
    12. }

⬆ 返回目录

事件

  • 24.1 当给事件附加数据时(无论是 DOM 事件还是私有事件),传入一个哈希而不是原始值。这样可以让后面的贡献者增加更多数据到事件数据而无需找出并更新事件的每一个处理器。例如,不好的写法:

    1. // bad
    2. $(this).trigger('listingUpdated', listing.id);
    3. ...
    4. $(this).on('listingUpdated', function(e, listingId) {
    5. // do something with listingId
    6. });

    更好的写法:

    1. // good
    2. $(this).trigger('listingUpdated', { listingId : listing.id });
    3. ...
    4. $(this).on('listingUpdated', function(e, data) {
    5. // do something with data.listingId
    6. });

    ⬆ 返回目录

jQuery

  • 25.1 使用 $ 作为存储 jQuery 对象的变量名前缀。

    1. // bad
    2. const sidebar = $('.sidebar');
    3. // good
    4. const $sidebar = $('.sidebar');
  • 25.2 缓存 jQuery 查询。

    1. // bad
    2. function setSidebar() {
    3. $('.sidebar').hide();
    4. // ...stuff...
    5. $('.sidebar').css({
    6. 'background-color': 'pink'
    7. });
    8. }
    9. // good
    10. function setSidebar() {
    11. const $sidebar = $('.sidebar');
    12. $sidebar.hide();
    13. // ...stuff...
    14. $sidebar.css({
    15. 'background-color': 'pink'
    16. });
    17. }
  • 25.3 对 DOM 查询使用层叠 $('.sidebar ul') 或 父元素 > 子元素 $('.sidebar > ul')jsPerf

  • 25.4 对有作用域的 jQuery 对象查询使用 find

    1. // bad
    2. $('ul', '.sidebar').hide();
    3. // bad
    4. $('.sidebar').find('ul').hide();
    5. // good
    6. $('.sidebar ul').hide();
    7. // good
    8. $('.sidebar > ul').hide();
    9. // good
    10. $sidebar.find('ul').hide();

⬆ 返回目录