Airbnb前端规范之javascript编码规范

1 引用

1.1 对所有的引用使用 const ,不要使用 var。

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

// bad
  var a = 1;
  var b = 2;

// good
  const a = 1;
  const b = 2;

1.2 如果一定需要可变动的引用,使用 let 代替 var。

(因为 let 是块级作用域,而 var 是函数作用域。)

// bad
  var count = 1;
  if (true) {
    count += 1;
  }

// good, use the let.
  let count = 1;
  if (true) {
    count += 1;
  }

2 对象

2.1 使用字面值创建对象。

// bad
const item = new Object();

// good
const item = {};

2.2 使用对象方法的简写。

// bad
const atom = {
  value: 1,
  addValue: function (value) {
    return atom.value + value;
  },
};
// good
const atom = {
  value: 1,
  addValue(value) {
    return atom.value + value;
  },
};

2.3 使用对象属性值的简写。

const lukeSkywalker = 'Luke Skywalker';
// bad
  const obj = {
    lukeSkywalker: lukeSkywalker,
  };
// good
  const obj = {
    lukeSkywalker,
  };

2.4 不要直接调用 Object.prototype 的方法,如:hasOwnProperty, propertyIsEnumerable, 和 isPrototypeOf

// bad
console.log(object.hasOwnProperty(key));

// good
console.log(Object.prototype.hasOwnProperty.call(object, key));

// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
/* or */
const has = require('has');
…
console.log(has.call(object, key));

2.5 浅拷贝对象的时候最好是使用 … 操作符而不是 Object.assign

// very bad
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // this mutates `original`
delete copy.a; // so does this
// bad const original = { a: 1, b: 2 }; const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 } // good const original = { a: 1, b: 2 }; const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 } const { a, ...noA } = copy; // noA => { b: 2, c: 3 }

3 数组

3.1 使用字面值创建数组。eslint: no-array-constructor

// bad
const items = new Array();

// good
const items = [];

3.2 使用拓展运算符 … 复制数组。

// bad
const items = new Array();

// good
const items = [];

// bad
const len = items.length;
const itemsCopy = [];
let i;

for(i = 0;i <len;i++){
  itemsCopy[i] = items[i];
}

// good
const itemsCopy = [...items];

3.3 使用 Array#from 把一个类数组对象转换成数组

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

4 函数

4.1 使用函数声明代替函数表达式

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

// bad
  const foo = function () {
  };

  // good
  function foo() {
  }

4.2 函数表达式:

// 立即调用的函数表达式 (IIFE)
(() => {
   console.log('Welcome to the Internet. Please follow me.');
})();

4.3 永远不要在一个非函数代码块(if、while 等)中声明一个函数,把那个函数赋给一个变量。浏览器允许你这么做,但它们的解析表现不一致

// bad
if (currentUser) {
  function test() {
    console.log('Nope.');
  }
}

// good
let test;
if (currentUser) {
  test = () => {
    console.log('Yup.');
  };
}

4.4 不要使用 arguments。可以选择 rest 语法 … 替代

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

// bad
  function concatenateAll() {
    const args = Array.prototype.slice.call(arguments);
    return args.join('');
  }

  // good
  function concatenateAll(...args) {
    return args.join('');
  }

5 箭头函数

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

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

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

// bad
  [1, 2, 3].map(function (x) {
    return x * x;
  });

  // good
  [1, 2, 3].map((x) => {
    return x * x;
  });

5.2 如果一个函数适合用一行写出并且只有一个参数,那就把花括号、圆括号和 return 都省略掉。如果不是,那就不要省略

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

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

  // good
  [1, 2, 3].map(x => x * x);

  // good
  [1, 2, 3].reduce((total, n) => {
    return total + n;
  }, 0);

6 构造器

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

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

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


  // good
  class Queue {
    constructor(contents = []) {
      this._queue = [...contents];
    }
    pop() {
      const value = this._queue[0];
      this._queue.splice(0, 1);
      return value;
    }
  }

  

6.2 使用 extends 继承。

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

6.3 方法可以返回 this 来帮助链式调用。

7 模块

7.1 总是使用模组 (import/export)

7.2 不要使用通配符 import

// bad
  import * as AirbnbStyleGuide from './AirbnbStyleGuide';

// good
  import AirbnbStyleGuide from './AirbnbStyleGuide';

  

7.3 不要从 import 中直接 export

// bad
  // filename es6.js
  export { es6 as default } from './airbnbStyleGuide';

// good
  // filename es6.js
  import { es6 } from './AirbnbStyleGuide';
  export default es6;

  

8 Iterators and Generators

8.1 不要使用 iterators,使用高阶函数例如 map() 和 reduce() 替代 for-of

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

 const numbers = [1, 2, 3, 4, 5];

  // bad
  let sum = 0;
  for (let num of numbers) {
    sum += num;
  }

  sum === 15;

  // good
  let sum = 0;
  numbers.forEach((num) => sum += num);
  sum === 15;

  // best (use the functional force)
  const sum = numbers.reduce((total, num) => total + num, 0);
  sum === 15;

8.2 现在还不要使用 generators?

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

9 变量

9.1 一直使用 const 来声明变量

如果不这样做就会产生全局变量。我们需要避免全局命名空间的污染。

// bad
superPower = new SuperPower();

// good
const superPower = new SuperPower();

  

9.2 使用 const 声明每一个变量

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

9.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;

9.4 在你需要的地方给变量赋值,但请把它们放在一个合理的位置

let 和 const 是块级作用域而不是函数作用域。

10 提升

10.1 var 声明会被提升至该作用域的顶部,但它们赋值不会提升。

let 和 const 被赋予了一种称为「暂时性死区(Temporal Dead Zones, TDZ)」的概念。这对于了解为什么 type of 不再安全相当重要。

10.2 匿名函数表达式的变量名会被提升,但函数内容并不会。

10.3 命名的函数表达式的变量名会被提升,但函数名和函数函数内容并不会。

10.4 函数声明的名称和函数体都会被提升。

11 比较运算符 & 等号

11.1 优先使用 === 和 !== 而不是 == 和 !=.

11.2 条件表达式例如 if 语句通过抽象方法 ToBoolean 强制计算它们的表达式并且总是遵守下面的规则:

o 对象 被计算为 true

o Undefined 被计算为 false

o Null 被计算为 false

o 布尔值 被计算为 布尔的值

o 数字 如果是 +0、-0、或 NaN 被计算为 false, 否则为 true

o 字符串 如果是空字符串 ” 被计算为 false,否则为 true

12 注释

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

// bad
// make() returns a new element
// based on the passed in tag name
//
// @param {String} tag
// @return {Element} element
function make(tag) {

  // ...stuff...

  return element;
}

// good
/**
 * make() returns a new element
 * based on the passed in tag name
 *
 * @param {String} tag
 * @return {Element} element
 */
function make(tag) {

  // ...stuff...

  return element;
}

  

12.2 使用 // 作为单行注释。在注释对象上面另起一行使用单行注释。在注释前插入空行。

12.3 给注释增加 FIXME 或 TODO 的前缀

帮助其他开发者快速了解这是一个需要复查的问题,或是给需要实现的功能提供一个解决方式。这将有别于常见的注释,因为它们是可操作的。使用 FIXME – need to figure this out 或者 TODO – need to implement。

12.4 使用 // FIXME: 标注问题。

class Calculator {
  constructor() {
    // FIXME: shouldn't use a global here
    total = 0;
  }
}

  

12.5 使用 // TODO: 标注问题的解决方式。

class Calculator {
  constructor() {
    // TODO: total should be configurable by an options param
    this.total = 0;
  }
}

13 空白

13.1 使用 2 个空格作为缩进。

13.2 在花括号前要放一个空格。

13.3 在控制语句(if、while 等)的小括号前放一个空格。

在函数调用及声明中,不在函数的参数列表前加空格。

13.4 在文件末尾插入一个空行。

13.5 在使用长方法链时进行缩进。使用放置在前面的点 . 强调这是方法调用而不是新语句。