一 Airbnb javascript编码规范
1 引用
1.1 对所有的引用使用 const ,不要使用 var。
eslint: prefer-const, no-const-assign
这能确保你无法对引用重新赋值,也不会导致出现 bug 或难以理解
// bad
var a = 1;
var b = 2;
// good
const a = 1;
const b = 2;
1.2 如果一定需要可变动的引用,使用 let 代替 var。
eslint: no-var jscs: disallowVar
因为 let 是块级作用域,而 var 是函数作用域。
// bad
var count = 1;
if (true) {
count += 1;
}
// good, use the let.
let count = 1;
if (true) {
count += 1;
}
1.3 不能出现声明之后没用到的变量
如果在模块外部,用var创建了一个被其他模块代码引用的变量。可以用/ exported variableName / 注释表示此变量已导出。
2 对象
2.1 使用字面值创建对象。
eslint: no-new-object
// bad
const item = new Object();
// good
const item = {};
2.2 使用对象方法的简写。
eslint: object-shorthand jscs: requireEnhancedObjectLiterals
// 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 使用对象属性值的简写。
eslint: object-shorthand jscs: requireEnhancedObjectLiterals
这样更短更有描述性。
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 }
2.6 禁止对象字面量属性名称使用引号
当没有严格要求时,禁止对象字面量属性名称使用引号
var a = { 'name': 'lisi' }; //bad
var a = { name: 'lisi' }; //good
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);
3.4 数组方法的回调函数中必须有 return 语句
该规则发现以下方法的回调函数,然后检查return语句的使用。
Array.from Array.prototype.every Array.prototype.filter Array.prototype.find Array.prototype.findIndex Array.prototype.map Array.prototype.reduce Array.prototype.reduceRight Array.prototype.some Array.prototype.sort 以上类型的数据。
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('');
}
4.5 function的左括号之前空格。
anonymous: 'always', // 匿名函数有空格 named: 'never', //命名函数没有空格 asyncArrow: 'always' //箭头函数有空格
选项 {"anonymous": "always", "named": "never", "asyncArrow": "always"} 的 正确 代码示例:
/*eslint space-before-function-paren: ["error", {"anonymous": "always", "named": "never", "asyncArrow": "always"}]*/
/*eslint-env es6*/
function foo() { // 命名函数没有空格
// ...
}
var bar = function () { // 匿名函数有空格
// ...
};
class Foo {
constructor() { // 命名函数没有空格
// ...
}
}
var foo = {
bar() { // 命名函数没有空格
// ...
}
};
var foo = async (a) => await a //箭头函数也有空格
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 使用 2 个空格作为缩进。
6.2 在花括号前要放一个空格(代码块之前空格)。
6.3 在控制语句(if、while 等)的小括号前放一个空格。
在函数调用及声明中,不在函数的参数列表前加空格。
6.4 在文件末尾插入一个空行。
6.5 在使用长方法链时进行缩进。使用放置在前面的点 . 强调这是方法调用而不是新语句。
6.6 强制逗号之前无空格,逗号之后有空格
var a = {a:'sina', b: 'baidu'};
6.7 对象字面量中,强制冒号之前不能有空格,冒号之后要有空格,且只能有一个空格
var a = {a:'sina', b: 'baidu'};
6.8 分号前无空格,分号之后有空格。
正确 代码示例:
/*eslint semi-spacing: "error"*/
var foo;
var foo; var bar;
throw new Error("error");
while (a) { break; }
for (i = 0; i < 10; i++) {}
for (;;) {}
if (true) {;}
;foo();
6.8 关键字前后有空格。
if (a<0) {
a++;
} else if {
a = 1;
}
6.9 禁止块语句开始或末尾有空行
错误:
if (a)
{
b();
}
正确:
if (a)
{
b();
}
7 引号
尽量使用单引号
8 比较运算符 & 等号
8.1 优先使用 === 和 !== 而不是 == 和 !=.
8.2 条件表达式例如 if 语句通过抽象方法 ToBoolean 强制计算它们的表达式并且总是遵守下面的规则:
o 对象 被计算为 true o Undefined 被计算为 false o Null 被计算为 false o 布尔值 被计算为 布尔的值 o 数字 如果是 +0、-0、或 NaN 被计算为 false, 否则为 true o 字符串 如果是空字符串 ” 被计算为 false,否则为 true
9 注释
9.0 "//" 单行注释,双斜杠后面要跟一个空格或tab。
9.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;
}
9.2 使用 // 作为单行注释。在注释对象上面另起一行使用单行注释。在注释前插入空行。
9.3 给注释增加 FIXME 或 TODO 的前缀
帮助其他开发者快速了解这是一个需要复查的问题,或是给需要实现的功能提供一个解决方式。这将有别于常见的注释,因为它们是可操作的。使用 FIXME – need to figure this out 或者 TODO – need to implement。
9.4 使用 // FIXME: 标注问题。
class Calculator {
constructor() {
// FIXME: shouldn't use a global here
total = 0;
}
}
9.5 使用 // TODO: 标注问题的解决方式。
class Calculator {
constructor() {
// TODO: total should be configurable by an options param
this.total = 0;
}
}
10 构造器
10.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;
}
}
10.2 使用 extends 继承。
为什么?因为 extends 是一个内建的原型继承方法并且不会破坏 instanceof。
10.3 方法可以返回 this 来帮助链式调用。
11 模块
11.1 总是使用模组 (import/export)
而不是其他非标准模块系统。你可以编译为你喜欢的模块系统。 为什么?模块就是未来,让我们开始迈向未来吧。
11.2 不要使用通配符 import
为什么?这样能确保你只有一个默认 export。
// bad import * as AirbnbStyleGuide from './AirbnbStyleGuide';
// good import AirbnbStyleGuide from './AirbnbStyleGuide';
11.3 不要从 import 中直接 export
为什么?虽然一行代码简洁明了,但让 import 和 export 各司其职让事情能保持一致。
// bad // filename es6.js export { es6 as default } from './airbnbStyleGuide';
// good // filename es6.js import { es6 } from './AirbnbStyleGuide'; export default es6;
12 Iterators and Generators
12.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;
12.2 现在还不要使用 generators?
为什么?因为它们现在还没法很好地编译到 ES5。 (目前Chrome 和 Node.js 的稳定版本都已支持 generators)
13 变量
13.1 一直使用 const 来声明变量
如果不这样做就会产生全局变量。我们需要避免全局命名空间的污染。
// bad superPower = new SuperPower();
// good const superPower = new SuperPower();
13.2 使用 const 声明每一个变量
为什么?增加新变量将变的更加容易,而且你永远不用再担心调换错 ; 跟 ,。
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 在你需要的地方给变量赋值,但请把它们放在一个合理的位置
为什么?let 和 const 是块级作用域而不是函数作用域。
14 提升
14.1 var 声明会被提升至该作用域的顶部,但它们赋值不会提升。
let 和 const 被赋予了一种称为「暂时性死区(Temporal Dead Zones, TDZ)」的概念。这对于了解为什么 type of 不再安全相当重要。
14.2 匿名函数表达式的变量名会被提升,但函数内容并不会。
14.3 命名的函数表达式的变量名会被提升,但函数名和函数函数内容并不会。
14.4 函数声明的名称和函数体都会被提升。
15. 要求使用拖尾逗号(comma-dangle)
当最后一个元素或属性与闭括号 ] 或 } 在 不同的行时,要求使用拖尾逗号;当在 同一行时,禁止使用拖尾逗号。
错误示例代码:
var foo = {
bar: "baz",
qux: "quux"
};
正确示例代码:
var foo = {
bar: "baz",
qux: "quux",
};
16. 句尾要求使用分号(semi)
要求在语句末尾使用分号。
错误代码示例:
/*eslint semi: ["error", "always"]*/
var name = "ESLint"
object.method = function() {
// ...
}
正确代码示例:
/*eslint semi: "error"*/
var name = "ESLint";
object.method = function() {
// ...
};
17. 强制使用一致的缩进 (indent)
详细请看indent具体讲解
配置文件代码:
// this option sets a specific tab width for your code
// http://eslint.org/docs/rules/indent
indent: ['error', 2, { //多行首行缩进两个空格
// switch语句,case要缩进两个空格
SwitchCase: 1,
//如果缩进设置为 2 个空格,VariableDeclarator 设置为 1,多行变量声明将会缩进 2 个空格
VariableDeclarator: 1,
//if语句块缩进两个空格
outerIIFEBody: 1,
// MemberExpression: null,
// CallExpression: {
// parameters: null,
// },
//function语句块缩进两个空格(参数和body都是)
FunctionDeclaration: {
parameters: 1,
body: 1
},
//function表达式进两个空格(参数和body都是)
FunctionExpression: {
parameters: 1,
body: 1
}
}],
正确代码示例:
/*eslint indent: ["error", 2, { "SwitchCase": 1 }]*/
switch(a){
case "a":
break;
case "b":
break;
}
var a,
b,
c;
let a,
b,
c;
const a = 1,
b = 2,
c = 3;
//function语句块
function foo(bar,
baz,
qux) {
qux();
}
//function表达式
var foo = function(bar,
baz,
qux) {
qux();
}
18. 强制在模块顶部调用require() (global-require)
此规则要求所有调用 require() 必须在模块顶部,与 ES6 中 import 和 export 语句(只能放在顶部)相同。
- 错误 代码示例:
/*eslint global-require: "error"*/
/*eslint-env es6*/
// 不可以在方法体里面,应该拿到方法外面
function readFile(filename, callback) {
var fs = require('fs');
fs.readFile(filename, callback);
}
// 不可以在条件语句块里
if (DEBUG) { require('debug'); }
// 不可以在switch语句块里
switch(x) { case '1': require('1'); break; }
// 不能在箭头函数的方法方法体里
var getModule = (name) => require(name);
// 不可以在方法体里面,应该拿到方法外面
function getModule(name) { return require(name); }
// 不能用到try catch语句块内
try {
require(unsafeModule);
} catch(e) {
console.log(e);
}
- 正确 代码示例:
/*eslint global-require: "error"*/
// all these variations of require() are ok
require('x');
var y = require('y');
var z;
z = require('z').initialize();
// requiring a module and using it in a function is ok
var fs = require('fs');
function readFile(filename, callback) {
fs.readFile(filename, callback)
}
// you can use a ternary to determine which module to require
var logger = DEBUG ? require('dev-logger') : require('logger');
// if you want you can require() at the end of your module
function doSomethingA() {}
function doSomethingB() {}
var x = require("x"),
z = require("z");
19. 要求驼峰拼写法 (camelcase)
详细介绍请看camelcase
配置文件代码:
// require camel case names
camelcase: ['error', { properties: 'never' }],
要求:所有名称驼峰拼写法命名,属性名除外
20. 强制在花括号中使用一致的空格 (object-curly-spacing)
"always" 要求花括号内有空格 (除了 {})
- 选项 "always" 的 错误 代码示例:
/* eslint object-curly-spacing: ["error", "always"] */
var obj = {'foo': 'bar'};
var obj = {'foo': 'bar' };
var obj = { baz: {'foo': 'qux'}, bar};
var obj = {baz: { 'foo': 'qux' }, bar};
var obj = {'foo': 'bar'
};
var obj = {
'foo':'bar'};
var {x} = y;
import {foo } from 'bar';
- 选项 "always" 的 正确 代码示例:
/* eslint object-curly-spacing: ["error", "always"] */
var obj = {};
var obj = { 'foo': 'bar' };
var obj = { 'foo': { 'bar': 'baz' }, 'qux': 'quxx' };
var obj = {
'foo': 'bar',
};
var { x } = y;
import { foo } from 'bar';
21 不常用的限制:
21.1 圈复杂度最多为11.
圈复杂度数量上表现为覆盖所有代码的独立现行路径条数。该规则允许设置一个圈复杂度阈值。 例如下面的function a的圈复杂度为3:
function a(x) {
if (true) {
return x; // 1st path
} else if (false) {
return x+1; // 2nd path
} else {
return 4; // 3rd path
}
}