Airbnb JavaScript 风格指南
本文已将原英文文档转写为双语格式,并对可能的难点提供了相应注解。
阿里巴巴JS规范官方文档地址: GitHub - Airbnb/javascript: JavaScript 风格指南
一、变量类型(Types)
-
1.1 基 元:当您访问基元类型时,您可以直接处理其值。Primitives: When you access a primitive type you work directly on its value.
-
string
-
number
-
boolean
-
null
-
undefined
-
symbol
-
bigint
JavaScriptconst foo = 1; let bar = foo; bar = 9; console.log(foo, bar); // => 1, 9
- Symbols 和 BigInts无法忠实地进行多填充,因此在定位到本身不支持它们的浏览器/环境时,不应使用它们。
-
-
1.2 复杂 类型:当您访问复杂类型时,您需要处理对其值的引用。Complex: When you access a complex type you work on a reference to its value.
-
object
-
array
-
function
JavaScriptconst foo = [1, 2]; const bar = foo; bar[0] = 9; console.log(foo[0], bar[0]); // => 9, 9
-
二、变量声明(Reference)
-
2.1 固定变量避免用
var
声明,请用const
。Useconst
for all of your references; avoid usingvar
. (.eslint:prefer-const
,no-const-assign
)为什么?这样可以确保无法重新分配引用.
JavaScript// bad var a = 1; var b = 2; // good const a = 1; const b = 2;
-
2.2 如果必须重新指定引用,请使用
let
代替var
。If you must reassign references, uselet
instead ofvar
.(.eslint:no-var
)为什么? 是块范围的,而不是函数范围的,如 。
let``var
JavaScript// bad var count = 1; if (true) { count += 1; } // good, use the let. let count = 1; if (true) { count += 1; }
-
2.3 请注意,
let
和const
都是块范围的,而var
是函数范围的。Note that bothlet
andconst
are block-scoped, whereasvar
is function-scoped.JavaScript// const and let only exist in the blocks they are defined in. { let a = 1; const b = 1; var c = 1; } console.log(a); // ReferenceError console.log(b); // ReferenceError console.log(c); // Prints 1
在上面的代码中,您可以看到引用
a
andb
将产生一个 ReferenceError,而c
包含数字。这是因为a
和b
是块范围,而c
是包含函数的范围。
三、Object
-
3.1 请使用文字语法创建对象。 Use the literal syntax for object creation. eslint:
no-new-object
JavaScript// bad const item = new Object(); // good const item = {};
-
3.2 请使用动态属性名称创建对象时,使用计算属性名称。 Use computed property names when creating objects with dynamic property names.
Why? They allow you to define all the properties of an object in one place.(在一个位置定义对象所有属性。)
JavaScriptfunction 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.3 请使用简写 定义对象的方法 属性。 Use object method shorthand. eslint:
object-shorthand
JavaScript// bad const atom = { value: 1, addValue: function (value) { return atom.value + value; }, }; // good const atom = { value: 1, addValue(value) { return atom.value + value; }, };
-
3.4 请使用简写 定义属性值。 Use property value shorthand. eslint:
object-shorthand
Why? It is shorter and descriptive. (短且描述性更强。)
JavaScriptconst lukeSkywalker = 'Luke Skywalker'; // bad const obj = { lukeSkywalker: lukeSkywalker, }; // good const obj = { lukeSkywalker, };
-
3.5 请将简写属性写在一处。 Group your shorthand properties at the beginning of your object declaration.
Why? It's easier to tell which properties are using the shorthand.
JavaScriptconst anakinSkywalker = 'Anakin Skywalker'; const lukeSkywalker = 'Luke Skywalker'; // bad const obj = { episodeOne: 1, twoJediWalkIntoACantina: 2, lukeSkywalker, episodeThree: 3, mayTheFourth: 4, anakinSkywalker, }; // good const obj = { lukeSkywalker, anakinSkywalker, episodeOne: 1, twoJediWalkIntoACantina: 2, episodeThree: 3, mayTheFourth: 4, };
- 3.6 引号只加在属于'非法标识符'的属性名上。 Only quote properties that are invalid identifiers. eslint:
quote-props
Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.
为什么?一般来说,我们认为它主观上更容易阅读。它改进了语法高亮,并且也更容易被许多 JS 引擎优化。
JavaScript
// bad
const bad = {
'foo': 3,
'bar': 4,
'data-blah': 5,
};
// good
const good = {
foo: 3,
bar: 4,
'data-blah': 5,
};
解释:标识符(Identifier)是JavaScript的重要概念,包括变量名、函数名、参数名、属性名、类名等等。
合法的标识符 有以下强制规则:
1. 第一个字符,可以是任意 Unicode 字母(包括英文字母和其他语言的字母),以及美元符号$和下划线_。不能是数字。
2. 第二个字符及后面的字符,除了 Unicode 字母、美元符号和下划线,还可以用数字0-9。
3. 标识符不能包含空格。
4. 标识符名称不能是 JavaScript 关键字或 JavaScript 保留字。
5. 标识符区分大小写。
例如:在上文代码示例中,
foo
和bar
是合法标识符,而data-blah
是非法标识符。
-
3.7 请不要直接通过对象实例 调用Object原型 上的方法。 Do not call
Object.prototype
methods directly, such as,hasOwnProperty
,propertyIsEnumerable
andisPrototypeOf
. (eslint:no-prototype-builtins
)Why? These methods may be shadowed by properties on the object in question - consider
{ hasOwnProperty: false }
- or, the object may be a null object (Object.create(null)
). In modern browsers that support ES2022, or with a polyfill such as npmjs.com/object.haso...,Object.hasOwn
can also be used as an alternative toObject.prototype.hasOwnProperty.call
.
解释:一开始使用Object.create(null)
创建的对象实例是没有prototype的,所以没有任何原型方法,这种情况下调用原型方法只会得到undefined。 而且对象实例的原型方法也可能会被{ hasOwnProperty: false }
这类的指令隐藏。所以要使用Object.原型对象而不是 对象实例.原型方法。
即使用
Object.prototype.hasOwnProperty.call(object, key)
或者Object.hasOwn(object, key)
可以确保调用到正确的方法。JavaScript// object为一个对象实例 // bad console.log(object.hasOwnProperty(key)); // good console.log(Object.prototype.hasOwnProperty.call(object, key)); // better const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope. console.log(has.call(object, key)); // best console.log(Object.hasOwn(object, key)); // only supported in browsers that support ES2022 /* or */ import has from 'has'; // https://www.npmjs.com/package/has console.log(has(object, key)); /* or */ console.log(Object.hasOwn(object, key)); // https://www.npmjs.com/package/object.hasown
-
3.8 对象浅拷贝时,首选
...
展开运算符而非Object.assign
。 Prefer the object spread syntax overObject.assign
to shallow-copy objects. Use the object rest parameter syntax to get a new object with certain properties omitted. eslint:prefer-object-spread
浅拷贝时,使用
Object.assign()
合并的对象与生成的对象之间可能会互相影响。而使用...
相对稳定,不会互相影响。JavaScript// 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 }
四、Array
-
4.1 请使用字面量语法创建数组,而非
new Array()
。 Use the literal syntax for array creation. eslint:no-array-constructor
js// bad const items = new Array(); // good const items = [];
-
4.2 请使用
.push()
而非直接赋值将项目添加到数组中。Use Array#push instead of direct assignment to add items to an array.jsconst someStack = []; // bad someStack[someStack.length] = 'abracadabra'; // good someStack.push('abracadabra');
-
4.3 请使用
...
浅拷贝数组。Use array spreads...
to copy arrays.js// bad const len = items.length; const itemsCopy = []; let i; for (i = 0; i < len; i += 1) { itemsCopy[i] = items[i]; } // good const itemsCopy = [...items];
-
4.4 要将可迭代对象转为数组,最好使用
...
代替Array.from
。 To convert an iterable object to an array, use spreads...
instead ofArray.from
.jsconst foo = document.querySelectorAll('.foo'); // good const nodes = Array.from(foo); // best const nodes = [...foo];
-
4.5 将类数组对象转换为数组,请使用
Array.from
。 UseArray.from
for converting an array-like object to an array.jsconst arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 }; // bad const arr = Array.prototype.slice.call(arrLike); // good const arr = Array.from(arrLike);
-
4.6使用
Array.from
而非...
+.map()
,可避免创建中间数组。UseArray.from
instead of spread...
for mapping over iterables, because it avoids creating an intermediate array.jsconst foo=[1,3,5,2,6]; const bar=()=>{return 7;} // bad const baz = [...foo].map(bar);// [7,7,7,7,7] // good const baz = Array.from(foo, bar);// [7,7,7,7,7]
-
4.7请在书组回调方法中使用
return
。如果函数体由一条返回一个表达式的语句组成, 并且这个表达式没有副作用, 这个时候可以忽略return,遵循 8.2。 Use return statements in array method callbacks. It's ok to omit the return if the function body consists of a single statement returning an expression without side effects, following 8.2. (eslint:array-callback-return
)js// good [1, 2, 3].map((x) => { const y = x + 1; return x * y; }); // good [1, 2, 3].map((x) => x + 1); // bad - no returned value means `acc` becomes undefined after the first iteration [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { const flatten = acc.concat(item); }); // good [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { const flatten = acc.concat(item); return flatten; }); // bad inbox.filter((msg) => { const { subject, author } = msg; if (subject === 'Mockingbird') { return author === 'Harper Lee'; } else { return false; } }); // good inbox.filter((msg) => { const { subject, author } = msg; if (subject === 'Mockingbird') { return author === 'Harper Lee'; } return false; });
-
4.8 如果一个数组有很多行,在数组的
[
后和]
前换行。 Use line breaks after opening array brackets and before closing array brackets, if an array has multiple linesjs// bad const arr = [ [0, 1], [2, 3], [4, 5], ]; // bad const objectInArray = [{ id: 1, }, { id: 2, }]; // bad const numberInArray = [ 1, 2, ]; // good const arr = [[0, 1], [2, 3], [4, 5]]; // good const objectInArray = [ { id: 1, }, { id: 2, }, ]; // good const numberInArray = [ 1, 2, ];
五、解构
-
5.1在访问和使用对象的多个属性时请首选对象解构 。 Use object destructuring when accessing and using multiple properties of an object. (eslint:
prefer-destructuring
)Why? Destructuring saves you from creating temporary references for those properties, and from repetitive access of the object. Repeating object access creates more repetitive code, requires more reading, and creates more opportunities for mistakes. Destructuring objects also provides a single site of definition of the object structure that is used in the block, rather than requiring reading the entire block to determine what is used.
通过解构,您可以避免为这些属性创建临时引用。
js// bad function getFullName(user) { const firstName = user.firstName; const lastName = user.lastName; return `${firstName} ${lastName}`; } // good function getFullName(user) { const { firstName, lastName } = user; return `${firstName} ${lastName}`; } // best function getFullName({ firstName, lastName }) { return `${firstName} ${lastName}`; }
-
5.2 首选数组解构 。 Use array destructuring. eslint:
prefer-destructuring
jsconst arr = [1, 2, 3, 4]; // bad const first = arr[0]; const second = arr[1]; // good const [first, second] = arr;
-
5.3 对多个返回值使用对象解构,而不是数组解构。 Use object destructuring for multiple return values, not array destructuring.
Why? You can add new properties over time or change the order of things without breaking call sites.
不依赖于返回值的顺序,更可读
js// bad function processInput(input) { // then a miracle occurs return [left, right, top, bottom]; } // the caller needs to think about the order of return data const [left, __, top] = processInput(input); // good function processInput(input) { // then a miracle occurs return { left, right, top, bottom }; } // the caller selects only the data they need const { left, top } = processInput(input);
六、String
-
6.1 String类型请统一用单引号
''
。 Use single quotes''
for strings. eslint:quotes
js// bad const name = "Capt. Janeway"; // bad - template literals should contain interpolation or newlines const name = `Capt. Janeway`; // good const name = 'Capt. Janeway';
-
6.2 一个字符串不要通过连接符换行,超长也写在一行。 Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation.
Why? Broken strings are painful to work with and make code less searchable.
不好用,且可读性差。
js// bad 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.'; // bad 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.'; // good 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.';
-
6.3 用字符串模板而不是
+
来拼接字符串。 When programmatically building up strings, use template strings instead of concatenation. (eslint:prefer-template
template-curly-spacing
)Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.
js// bad function sayHi(name) { return 'How are you, ' + name + '?'; } // bad function sayHi(name) { return ['How are you, ', name, '?'].join(); } // bad function sayHi(name) { return `How are you, ${ name }?`; } // good function sayHi(name) { return `How are you, ${name}?`; }
- 6.4 永远不要在字符串中用
eval()
,漏洞太多。 Never useeval()
on a string; it opens too many vulnerabilities. (eslint:no-eval
)
-
6.5 不要使用不必要的转义字符。Do not unnecessarily escape characters in strings. (eslint:
no-useless-escape
)Why? Backslashes harm readability, thus they should only be present when necessary.
反斜线可读性差,只在必要时使用
js// bad const foo = ''this' \i\s "quoted"'; // good const foo = ''this' is "quoted"'; const foo = `my name is '${name}'`;
七、Function
-
7.1 用命名函数表达式而不是函数声明。 Use named function expressions instead of function declarations. (eslint:
func-style
,func-names
)Why? Function declarations are hoisted, which means that it's easy - too easy - to reference the function before it is defined in the file. This harms readability and maintainability. If you find that a function's definition is large or complex enough that it is interfering with understanding the rest of the file, then perhaps it's time to extract it to its own module! Don't forget to explicitly name the expression, regardless of whether or not the name is inferred from the containing variable (which is often the case in modern browsers or when using compilers such as Babel). This eliminates any assumptions made about the Error's call stack. (Discussion)
函数声明作用域会提升,降低了代码可读性和可维护性。如果你发现一个函数又大又复杂,这个函数妨碍这个文件其他部分的理解性,这可能就是时候把这个函数单独抽成一个模块了。
js// bad 函数声明 function foo() { // ... } // bad 匿名函数表达式 const foo = function () { // ... }; // good 命名函数表达式 // 函数表达式名和声明的函数名是不一样的 const short = function longUniqueMoreDescriptiveLexicalFoo() { // ... };
-
7.2 将立即执行函数包裹在圆括号里。Wrap immediately invoked function expressions in parentheses. eslint:
wrap-iife
日常开发中,很少用到立即执行函数
js// immediately-invoked function expression (IIFE) (function () { console.log('Welcome to the Internet. Please follow me.'); }());
-
7.3不要在非函数块(if、while等等)内声明函数。而是把这个函数分配给一个变量。浏览器会允许你这样做,但浏览器解析方式不同,结果也许会有差异。 Never declare a function in a non-function block (
if
,while
, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears. (eslint:no-loop-func
)
js
// bad
if (currentUser) {
function test() {
console.log('Nope.');
}
}
// good
let test;
if (currentUser) {
test = () => {
console.log('Yup.');
};
}
- 7.4注意: 在ECMA-262中 [块
block
] 的定义是: 一系列的语句; 但是函数声明不是一个语句。 函数表达式是一个语句。 Note: ECMA-262 defines ablock
as a list of statements. A function declaration is not a statement.
-
7.5 永远不要用
arguments
命名参数。它的优先级高于每个函数作用域自带的arguments
对象, 所以会导致函数自带的arguments
值被覆盖。 Never name a parameterarguments
. This will take precedence over thearguments
object that is given to every function scope.js// bad function foo(name, options, arguments) { // ... } // good function foo(name, options, args) { // ... }
-
7.6优先使用rest语法
...
,而不是arguments
。 Never usearguments
, opt to use rest syntax...
instead. (eslint:prefer-rest-params
)Why?
...
is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like likearguments
....
更明确你想用哪些参数。js// bad function concatenateAll() { const args = Array.prototype.slice.call(arguments); return args.join(''); } // good function concatenateAll(...args) { return args.join(''); }
-
7.7 使用默认参数语法,而不是在函数里对参数重新赋值改变函数参数。Use default parameter syntax rather than mutating function arguments.
js// really bad function handleThings(opts) { // No! We shouldn't mutate function arguments. // Double bad: if opts is falsy it'll be set to an object which may // be what you want but it can introduce subtle bugs. // 虽然你想这么写, 但是这个会带来一些细微的bug // 如果 opts 的值为 false, 它会被赋值为 {} opts = opts || {}; // ... } // still bad function handleThings(opts) { if (opts === void 0) { opts = {}; } // ... } // good 默认参数语法 function handleThings(opts = {}) { // ... }
-
7.8 使用默认参数时,需要避免副作用。 Avoid side effects with default parameters.
避免使用令人困惑的默认参数。
jslet b = 1; // bad function count(a = b++) { console.log(a); } count(); // 1 count(); // 2 count(3); // 3 count(); // 3
-
7.9 始终将默认参数放在最后。 Always put default parameters last. (eslint:
default-param-last
)js// bad function handleThings(opts = {}, name) { // ... } // good function handleThings(name, opts = {}) { // ... }
-
7.10 不要用 Function 创建函数。Never use the Function constructor to create a new function. (eslint:
no-new-func
)Why? Creating a function in this way evaluates a string similarly to
eval()
, which opens vulnerabilities.类似于
eval()
,可能会产生漏洞,加大XSS攻击风险。js// bad const add = new Function('a', 'b', 'return a + b'); // still bad const subtract = Function('a', 'b', 'return a - b');
-
7.11 函数签名部分要有空格。Spacing in a function signature. (eslint:
space-before-function-paren
space-before-blocks
)Why? Consistency is good, and you shouldn't have to add or remove a space when adding or removing a name.
可保证一致性,在添加或删除名称时不必添加或删除空格。
js// bad const f = function(){}; const g = function (){}; const h = function() {}; // good const x = function () {}; const y = function a() {};
-
7.12 永远不要改参数。Never mutate parameters. (eslint:
no-param-reassign
)Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller.
js// bad function f1(obj) { obj.key = 1; } // good function f2(obj) { const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1; }
-
7.13 不要对参数重新赋值。Never reassign parameters. eslint:
no-param-reassign
Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the
arguments
object. It can also cause optimization issues, especially in V8.js// bad function f1(a) { a = 1; // ... } function f2(a) { if (!a) { a = 1; } // ... } // good function f3(a) { const b = a || 1; // ... } function f4(a = 1) { // ... }
-
7.14 首选...
。Prefer the use of the spread syntax...
to call variadic functions. (eslint:prefer-spread
)Why? It's cleaner, you don't need to supply a context, and you can not easily compose
new
withapply
.js// bad const x = [1, 2, 3, 4, 5]; console.log.apply(console, x); // good const x = [1, 2, 3, 4, 5]; console.log(...x); // bad new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5])); // good new Date(...[2016, 8, 5]);
- 7.15 具有多行签名或调用的函数应像本指南中的其他多行列表一样缩进:每个项目单独在一行上,最后一项上有一个逗号。Functions with multiline signatures, or invocations, should be indented just like every other multiline list in this guide: with each item on a line by itself, with a trailing comma on the last item. (eslint: function-paren-newline
)
js
// bad
function foo(bar,
baz,
quux) {
// ...
}
// good
function foo(
bar,
baz,
quux,
) {
// ...
}
// bad
console.log(foo,
bar,
baz);
// good
console.log(
foo,
bar,
baz,
);
八、箭头函数
-
8.1 果要用匿名函数做回调,最好使用箭头函数。When you must use an anonymous function (as when passing an inline callback), use arrow function notation. (eslint:
prefer-arrow-callback
,arrow-spacing
)简洁
js// bad [1, 2, 3].map(function (x) { const y = x + 1; return x * y; }); // good [1, 2, 3].map((x) => { const y = x + 1; return x * y; });
-
8.2 如果函数体由一个没有副作用的单个语句组成,去掉大括号和 return。否则,保留大括号且使用
return
语句。If the function body consists of a single statement returning an expression without side effects, omit the braces and use the implicit return. Otherwise, keep the braces and use areturn
statement. (eslint:arrow-parens
,arrow-body-style
)Why? Syntactic sugar. It reads well when multiple functions are chained together.
语法糖,可读性更好。
js// bad [1, 2, 3].map((number) => { const nextNumber = number + 1; `A string containing the ${nextNumber}.`; }); // good [1, 2, 3].map((number) => `A string containing the ${number + 1}.`); // good [1, 2, 3].map((number) => { const nextNumber = number + 1; return `A string containing the ${nextNumber}.`; }); // good [1, 2, 3].map((number, index) => ({ [index]: number, })); // No implicit return with side effects function foo(callback) { const val = callback(); if (val === true) { // Do something if callback returns true } } let bool = false; // bad foo(() => bool = true); // good foo(() => { bool = true; });
-
8.3 如果表达式跨越多行,请将其括在括号中以提高可读性。In case the expression spans over multiple lines, wrap it in parentheses for better readability.
Why? It shows clearly where the function starts and ends.
它更清楚地显示了函数的开始和结束位置。
js// bad ['get', 'post', 'put'].map((httpMethod) => Object.prototype.hasOwnProperty.call( httpMagicObjectWithAVeryLongName, httpMethod, ) ); // good ['get', 'post', 'put'].map((httpMethod) => ( Object.prototype.hasOwnProperty.call( httpMagicObjectWithAVeryLongName, httpMethod, ) ));
-
8.4 为了清晰和一致,始终在参数周围加上括号。Always include parentheses around arguments for clarity and consistency. (eslint:
arrow-parens
)Why? Minimizes diff churn when adding or removing arguments.
为什么?在添加或删除参数时最大限度地减少差异改动。
js// bad [1, 2, 3].map(x => x * x); // good [1, 2, 3].map((x) => x * x); // bad [1, 2, 3].map(number => ( `A long string with the ${number}. It's so long that we don't want it to take up space on the .map line!` )); // good [1, 2, 3].map((number) => ( `A long string with the ${number}. It's so long that we don't want it to take up space on the .map line!` )); // bad [1, 2, 3].map(x => { const y = x + 1; return x * y; }); // good [1, 2, 3].map((x) => { const y = x + 1; return x * y; });
-
8.5 避免箭头函数语法
=>
和比较操作符<=, >=
混淆。Avoid confusing arrow function syntax (=>
) with comparison operators (<=
,>=
). (eslint:no-confusing-arrow
)js// bad const itemHeight = (item) => item.height <= 256 ? item.largeSize : item.smallSize; // bad const itemHeight = (item) => item.height >= 256 ? item.largeSize : item.smallSize; // good const itemHeight = (item) => (item.height <= 256 ? item.largeSize : item.smallSize); // good const itemHeight = (item) => { const { height, largeSize, smallSize } = item; return height <= 256 ? largeSize : smallSize; };
-
8.6 使用隐式返回时强制约束函数体在箭头后面。Enforce the location of arrow function bodies with implicit returns. (eslint:
implicit-arrow-linebreak
)js// bad (foo) => bar; (foo) => (bar); // good (foo) => bar; (foo) => (bar); (foo) => ( bar )
九、Classes & Constructors
-
9.1 始终用
class
,避免直接操作prototype
。Always useclass
. Avoid manipulatingprototype
directly.Why?
class
syntax is more concise and easier to reason about.语法更简洁可读
js// 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; } }
-
9.2 使用
extends
实现继承。Useextends
for inheritance.Why? It is a built-in way to inherit prototype functionality without breaking
instanceof
.它是一种在不破坏
instanceof
的情况下继承原型功能的内置方法。js// bad const inherits = require('inherits'); function PeekableQueue(contents) { Queue.apply(this, contents); } inherits(PeekableQueue, Queue); PeekableQueue.prototype.peek = function () { return this.queue[0]; }; // good class PeekableQueue extends Queue { peek() { return this.queue[0]; } }
-
9.3 方法可以返回
this
来实现方法链。Methods can returnthis
to help with method chaining.js// bad Jedi.prototype.jump = function () { this.jumping = true; return true; }; Jedi.prototype.setHeight = function (height) { this.height = height; }; const luke = new Jedi(); luke.jump(); // => true luke.setHeight(20); // => undefined // good class Jedi { jump() { this.jumping = true; return this; } setHeight(height) { this.height = height; return this; } } const luke = new Jedi(); luke.jump() .setHeight(20);
-
9.4 允许写一个自定义的 toString() 方法,但是要保证它是可以正常工作且没有副作用。It's okay to write a custom
toString()
method, just make sure it works successfully and causes no side effects.jsclass Jedi { constructor(options = {}) { this.name = options.name || 'no name'; } getName() { return this.name; } toString() { return `Jedi - ${this.getName()}`; } }
-
9.5 如果没有特殊说明,类有默认的构造方法。不用特意写一个空的构造函数或只是代表父类的构造函数。Classes have a default constructor if one is not specified. An empty constructor function or one that just delegates to a parent class is unnecessary. (eslint:
no-useless-constructor
)js// bad class Jedi { constructor() {} getName() { return this.name; } } // bad class Rey extends Jedi { constructor(...args) { super(...args); } } // good class Rey extends Jedi { constructor(...args) { super(...args); this.name = 'Rey'; } }
-
9.6 避免重复的类成员。Avoid duplicate class members. eslint:
no-dupe-class-members
Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug.
重复类成员会默默的执行最后一个,有重复肯定就是一个错误
js// bad class Foo { bar() { return 1; } bar() { return 2; } } // good class Foo { bar() { return 1; } } // good class Foo { bar() { return 2; } }
-
9.7 类方法应使用
this
或编写为静态方法,除非外部库或框架要求使用特定的非静态方法。作为实例方法,应表明它的行为基于接收器的属性而有所不同。Class methods should usethis
or be made into a static method unless an external library or framework requires using specific non-static methods. Being an instance method should indicate that it behaves differently based on properties of the receiver. (eslint:class-methods-use-this
)js// bad class Foo { bar() { console.log('bar'); } } // good - this is used class Foo { bar() { console.log(this.bar); } } // good - constructor is exempt class Foo { constructor() { // ... } } // good - static methods aren't expected to use this class Foo { static bar() { console.log('bar'); } }
十、Modules
-
10.1 在非标准模块系统上使用(
import
/export
)。或者随时换成其他的首选模块系统。Always use modules (import
/export
) over a non-standard module system. You can always transpile to your preferred module system.Why? Modules are the future, let's start using the future now.
js// bad const AirbnbStyleGuide = require('./AirbnbStyleGuide'); module.exports = AirbnbStyleGuide.es6; // ok import AirbnbStyleGuide from './AirbnbStyleGuide'; export default AirbnbStyleGuide.es6; // best import { es6 } from './AirbnbStyleGuide'; export default es6;
-
10.2 不要用 import * 这种通配符。Do not use wildcard imports.
Why? This makes sure you have a single default export。
这样可以确保您有一个默认导出。
js// bad import * as AirbnbStyleGuide from './AirbnbStyleGuide'; // good import AirbnbStyleGuide from './AirbnbStyleGuide';
-
10.3 不要直接从import中export。And do not export directly from an import.
Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent.
虽然单行很简洁,但有一种明确的导入方式和一种明确的导出方式可以使代码风格保持一致。
js// bad // filename es6.js export { es6 as default } from './AirbnbStyleGuide'; // good // filename es6.js import { es6 } from './AirbnbStyleGuide'; export default es6;
-
10.4 一个入口只 import 一次。Only import from a path in one place. (eslint:
no-duplicate-imports
)Why? Having multiple lines that import from the same path can make code harder to maintain.
从同一个路径下import多行会使代码难以维护
js// bad import foo from 'foo'; // ... some other imports ... // import { named1, named2 } from 'foo'; // good import foo, { named1, named2 } from 'foo'; // good import foo, { named1, named2, } from 'foo';
-
10.5 不要导出可变的绑定,尽量导出常量。Do not export mutable bindings. (eslint:
import/no-mutable-exports
)Why? Mutation should be avoided in general, but in particular when exporting mutable bindings. While this technique may be needed for some special cases, in general, only constant references should be exported. 虽然在某些场景下可能需要这种技术,但总的来说应该尽量导出常量。
js// bad let foo = 3; export { foo }; // good const foo = 3; export { foo };
-
10.6 在只有一个导出的模块里,用
export default
更好。In modules with a single export, prefer default export over named export. eslint:import/prefer-default-export
Why? To encourage more files that only ever export one thing, which is better for readability and maintainability.
鼓励使用更多文件,每个文件只做一件事情并导出,这样可读性和可维护性更好。
js// bad export function foo() {} // good export default function foo() {}
-
10.7
import
放在其他所有语句之前。Put allimport
s above non-import statements. eslint:import/first
Why? Since
import
s are hoisted, keeping them all at the top prevents surprising behavior.防止意外行为。
js// bad import foo from 'foo'; foo.init(); import bar from 'bar'; // good import foo from 'foo'; import bar from 'bar'; foo.init();
-
10.8 多行 import 应该缩进,就像多行数组和对象字面量。Multiline imports should be indented just like multiline array and object literals. eslint:
object-curly-newline
Why? The curly braces follow the same indentation rules as every other curly brace block in the style guide, as do the trailing commas.
js// bad import {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path'; // good import { longNameA, longNameB, longNameC, longNameD, longNameE, } from 'path';
-
10.9 在 import 语句里不允许 Webpack loader 语法。Disallow Webpack loader syntax in module import statements. (eslint:
import/no-webpack-loader-syntax
)Why? Since using Webpack syntax in the imports couples the code to a module bundler. Prefer using the loader syntax in
webpack.config.js
.最好是在
webpack.config.js
里写js// bad import fooSass from 'css!sass!foo.scss'; import barCss from 'style!css!bar.css'; // good import fooSass from 'foo.scss'; import barCss from 'bar.css';
-
10.10 导入应不包括 JavaScript 文件扩展名Do not include JavaScript filename extensions eslint:
import/extensions
Why? Including extensions inhibits refactoring, and inappropriately hardcodes implementation details of the module you're importing in every consumer.
包含扩展名会抑制重构,并且不恰当地对要导入的模块的实现细节进行硬编码。
js// bad import foo from './foo.js'; import bar from './bar.jsx'; import baz from './baz/index.jsx'; // good import foo from './foo'; import bar from './bar'; import baz from './baz';
十一、Iterators and Generators
-
11.1 不要用迭代器。用 JavaScript 高阶函数代替
for-in
、for-of
。Don't use iterators. Prefer JavaScript's higher-order functions instead of loops likefor-in
orfor-of
. eslint:no-iterator
no-restricted-syntax
Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
Usemap()
/every()
/filter()
/find()
/findIndex()
/reduce()
/some()
/ ... to iterate over arrays, andObject.keys()
/Object.values()
/Object.entries()
to produce arrays so you can iterate over objects.jsconst 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; // bad const increasedByOne = []; for (let i = 0; i < numbers.length; i++) { increasedByOne.push(numbers[i] + 1); } // good const increasedByOne = []; numbers.forEach((num) => { increasedByOne.push(num + 1); }); // best (keeping it functional) const increasedByOne = numbers.map((num) => num + 1);
-
11.2 现在不要用 generator。Don't use generators for now.
Why? They don't transpile well to ES5.
兼容性不好
-
11.3 如果你一定要用generator,或者你忽略我们的建议, 请确保它们的函数签名之间的空格是正确的。If you must use generators, or if you disregard our advice, make sure their function signature is spaced properly. (eslint:
generator-star-spacing
)Why?
function
and*
are part of the same conceptual keyword -*
is not a modifier forfunction
,function*
is a unique construct, different fromfunction
.function
和*
是同一概念,关键字*
不是function
的修饰符,function*
是一个和function
不一样的独特结构js// bad function * foo() { // ... } // bad const bar = function * () { // ... }; // bad const baz = function *() { // ... }; // bad const quux = function*() { // ... }; // bad function*foo() { // ... } // bad function *foo() { // ... } // very bad function * foo() { // ... } // very bad const wat = function * () { // ... }; // good function* foo() { // ... } // good const foo = function* () { // ... };
十二、Properties
-
12.1 访问属性时使用点符号。Use dot notation when accessing properties. (eslint:
dot-notation
)jsconst luke = { jedi: true, age: 28, }; // bad const isJedi = luke['jedi']; // good const isJedi = luke.jedi;
-
12.2 获取的属性是变量时用方括号。Use bracket notation
[]
when accessing properties with a variable.jsconst luke = { jedi: true, age: 28, }; function getProp(prop) { return luke[prop]; } const isJedi = getProp('jedi');
-
12.3 做幂运算时用幂操作符
**
。Use exponentiation operator**
when calculating exponentiations. (eslint:prefer-exponentiation-operator
.)js// bad const binary = Math.pow(2, 10); // good const binary = 2 ** 10;
十三、Variables
-
13.1 始终用
const
或let
声明变量。如果你不想遇到变量提升、全局变量的 bug 的话。Always useconst
orlet
to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that. (eslint:no-undef
prefer-const
)js// bad superPower = new SuperPower(); // good const superPower = new SuperPower();
-
13.2 每个变量单独用一个
const
或let
。Use oneconst
orlet
declaration per variable or assignment. eslint:one-var
Why? It's easier to add new variable declarations this way, and you never have to worry about swapping out a
;
for a,
or introducing punctuation-only diffs. You can also step through each declaration with the debugger, instead of jumping through all of them at once.方便调试,可以使用调试器逐步完成每个声明,而不是一次跳过所有声明。
js// 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
const
放一起,let
放一起。 Group all yourconst
s and then group all yourlet
s.Why? This is helpful when later on you might need to assign a variable depending on one of the previously assigned variables.
js// 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 变量声明放在合理的位置(在需要的时候分配)。Assign variables where you need them, but place them in a reasonable place.
Why?
let
andconst
are block scoped and not function scoped.js// bad - unnecessary function call function checkName(hasName) { const name = getName(); if (hasName === 'test') { return false; } if (name === 'test') { this.setName(''); return false; } return name; } // good // 在需要的时候分配 function checkName(hasName) { if (hasName === 'test') { return false; } const name = getName(); if (name === 'test') { this.setName(''); return false; } return name; }
-
13.5 不要使用链式变量分配。Don't chain variable assignments. eslint:
no-multi-assign
Why? Chaining variable assignments creates implicit global variables.
链式变量分配会创建隐式全局变量。
js// bad (function example() { let a = b = c = 1; // JavaScript 将其解释为 // let a = ( b = ( c = 1 ) ); // let 只对变量 a 起作用; 变量 b 和 c 都变成了全局变量 }()); console.log(a); // throws ReferenceError console.log(b); // 1 console.log(c); // 1 // good (function example() { let a = 1; let b = a; let c = a; }()); console.log(a); // throws ReferenceError console.log(b); // throws ReferenceError console.log(c); // throws ReferenceError // the same applies for `const`
-
13.6 不要使用一元递增递减运算符(
++
,--
)。Avoid using unary increments and decrements (++
,--
). (eslintno-plusplus
)Why? Per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application. It is also more expressive to mutate your values with statements like
num += 1
instead ofnum++
ornum ++
. Disallowing unary increment and decrement statements also prevents you from pre-incrementing/pre-decrementing values unintentionally which can also cause unexpected behavior in your programs.根据 eslint 文档,一元递增和递减语句受到自动分号插入的影响,并且可能会导致应用程序中的值递增或递减的静默错误。 使用num += 1 而不是 num++ 或代替语句来改变你的值也更具表现力。禁止一元递增和递减语句也会阻止您无意中预先递增/预递减值,从而减少程序出现意外行为。
js// bad const array = [1, 2, 3]; let num = 1; num++; --num; let sum = 0; let truthyCount = 0; for (let i = 0; i < array.length; i++) { let value = array[i]; sum += value; if (value) { truthyCount++; } } // good const array = [1, 2, 3]; let num = 1; num += 1; num -= 1; const sum = array.reduce((a, b) => a + b, 0); const truthyCount = array.filter(Boolean).length;
-
13.7 避免在
=
前/后换行。 如果你的语句超出max-len
, 那就用()
把这个值包起来再换行。Avoid linebreaks before or after=
in an assignment. If your assignment violatesmax-len
, surround the value in parens. (eslintoperator-linebreak
)Why? Linebreaks surrounding
=
can obfuscate the value of an assignment.=
周围的换行符可能会混淆赋的值。js// bad const foo = superLongLongLongLongLongLongLongLongFunctionName(); // bad const foo = 'superLongLongLongLongLongLongLongLongString'; // good const foo = ( superLongLongLongLongLongLongLongLongFunctionName() ); // good const foo = 'superLongLongLongLongLongLongLongLongString';
-
13.8 不允许有未使用的变量。Disallow unused variables. (eslint:
no-unused-vars
)Why? Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.
在代码中声明但未在代码中的任何位置使用的变量很可能是由于重构不完整而导致的错误。此类变量会占用代码中的空间,并可能导致读者混淆。
js// bad const some_unused_var = 42; // 定义却未使用 let y = 10; y = 5; // 用于修改自身的读取不算已使用 let z = 0; z = z + 1; // 参数定义了却未使用 function getX(x, y) { return x; } // good function getXPlusY(x, y) { return x + y; } const x = 1; const y = a + 2; alert(getXPlusY(x, y)); // 'type' is ignored even if unused because it has a rest property sibling. // This is a form of extracting an object that omits the specified keys. const { type, ...coords } = data; // 'coords' is now the 'data' object without its 'type' property.
十四、Hoisting
-
14.1 var 声明被提升。const 和 let 声明被赋予一个所谓的新概念Temporal Dead Zones (TDZ)。 重要的是要知道为什么 typeof不再安全。
var
declarations get hoisted to the top of their closest enclosing function scope, their assignment does not.const
andlet
declarations are blessed with a new concept called Temporal Dead Zones (TDZ). It's important to know why typeof is no longer safe.js// we know this wouldn't work (assuming there // is no notDefined global variable) function example() { console.log(notDefined); // => throws a ReferenceError } // creating a variable declaration after you // reference the variable will work due to // variable hoisting. Note: the assignment // value of `true` is not hoisted. function example() { console.log(declaredButNotAssigned); // => undefined var declaredButNotAssigned = true; } // the interpreter is hoisting the variable // declaration to the top of the scope, // which means our example could be rewritten as: function example() { let declaredButNotAssigned; console.log(declaredButNotAssigned); // => undefined declaredButNotAssigned = true; } // using const and let function example() { console.log(declaredButNotAssigned); // => throws a ReferenceError console.log(typeof declaredButNotAssigned); // => throws a ReferenceError const declaredButNotAssigned = true; }
-
14.2 匿名函数表达式和
var
情况相同。Anonymous function expressions hoist their variable name, but not the function assignment.jsfunction example() { console.log(anonymous); // => undefined anonymous(); // => TypeError anonymous is not a function var anonymous = function () { console.log('anonymous function expression'); }; }
-
14.3 已命名的函数表达式提升他的变量名,而不是函数名或函数体。Named function expressions hoist the variable name, not the function name or the function body.
jsfunction example() { console.log(named); // => undefined named(); // => TypeError named is not a function superPower(); // => ReferenceError superPower is not defined var named = function superPower() { console.log('Flying'); }; } // the same is true when the function name // is the same as the variable name. function example() { console.log(named); // => undefined named(); // => TypeError named is not a function var named = function named() { console.log('named'); }; }
-
14.4 函数声明则提升了函数名和函数体Function declarations hoist their name and the function body.
jsfunction example() { superPower(); // => Flying function superPower() { console.log('Flying'); } }
-
14.5 变量、类和函数在使用之前应先定义。Variables, classes, and functions should be defined before they can be used. (eslint:
no-use-before-define
)Why? When variables, classes, or functions are declared after being used, it can harm readability since a reader won't know what a thing that's referenced is. It's much clearer for a reader to first encounter the source of a thing (whether imported from another module, or defined in the file) before encountering a use of the thing.
当变量、类或函数在使用后被声明时,它可能会损害可读性,因为读者不会知道所引用的事物是什么。
js// bad // Variable a is being used before it is being defined. console.log(a); // this will be undefined, since while the declaration is hoisted, the initialization is not var a = 10; // Function fun is being called before being defined. fun(); function fun() {} // Class A is being used before being defined. new A(); // ReferenceError: Cannot access 'A' before initialization class A { } // `let` and `const` are hoisted, but they don't have a default initialization. // The variables 'a' and 'b' are in a Temporal Dead Zone where JavaScript // knows they exist (declaration is hoisted) but they are not accessible // (as they are not yet initialized). console.log(a); // ReferenceError: Cannot access 'a' before initialization console.log(b); // ReferenceError: Cannot access 'b' before initialization let a = 10; const b = 5; // good var a = 10; console.log(a); // 10 function fun() {} fun(); class A { } new A(); let a = 10; const b = 5; console.log(a); // 10 console.log(b); // 5
-
For more information refer to JavaScript Scoping & Hoisting by Ben Cherry.
十五、比较和相等运算符 Comparison Operators & Equality
-
15.2
if
等条件语句使用强制ToBoolean
抽象方法来评估它们的表达式,并且始终遵循以下简单规则:非值:Undefined、Null、+0、-0、NaN、''、false。Conditional statements such as theif
statement evaluate their expression using coercion with theToBoolean
abstract method and always follow these simple rules:- Objects evaluate to true
- Undefined evaluates to false
- Null evaluates to false
- Booleans evaluate to the value of the boolean
- Numbers evaluate to false if +0, -0, or NaN , otherwise true
- Strings evaluate to false if an empty string
''
, otherwise true
jsif ([0] && []) { // true // an array (even an empty one) is an object, objects will evaluate to true }
-
15.3 布尔值比较可以省略,但是字符串和数字要显示比较。Use shortcuts for booleans, but explicit comparisons for strings and numbers.
js// bad if (isValid === true) { // ... } // good if (isValid) { // ... } // bad if (name) { // ... } // good if (name !== '') { // ... } // bad if (collection.length) { // ... } // good if (collection.length > 0) { // ... }
-
15.4 For more information see Truth, Equality, and JavaScript by Angus Croll.
-
15.5
switch case
中,在case
和default
分句里用大括号创建一个块(如:let
,const
,function
, andclass
).Use braces to create blocks incase
anddefault
clauses that contain lexical declarations (e.g.let
,const
,function
, andclass
). (eslint:no-case-declarations
)Why? Lexical declarations are visible in the entire
switch
block but only get initialized when assigned, which only happens when itscase
is reached. This causes problems when multiplecase
clauses attempt to define the same thing.词汇声明在整个 switch 块中都是可见的,但只有在分配时才会被初始化,这只有在 case 达到时才会发生。当多个 case 子句尝试定义相同的事物时,会出现问题。
js// bad switch (foo) { case 1: let x = 1; break; case 2: const y = 2; break; case 3: function f() { // ... } break; default: class C {} } // good switch (foo) { case 1: { let x = 1; break; } case 2: { const y = 2; break; } case 3: { function f() { // ... } break; } case 4: bar(); break; default: { class C {} } }
-
15.6 三元表达式不应该嵌套,通常是单行表达式。Ternaries should not be nested and generally be single line expressions. eslint:
no-nested-ternary
js// bad const foo = maybe1 > maybe2 ? "bar" : value1 > value2 ? "baz" : null; // split into 2 separated ternary expressions const maybeNull = value1 > value2 ? 'baz' : null; // better const foo = maybe1 > maybe2 ? 'bar' : maybeNull; // best const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
-
15.7 避免不需要的三元表达式。Avoid unneeded ternary statements. eslint:
no-unneeded-ternary
js// bad const foo = a ? a : b; const bar = c ? true : false; const baz = c ? false : true; const quux = a != null ? a : b; // good const foo = a || b; const bar = !!c; const baz = !c; const quux = a ?? b;
-
15.8 混合操作符时,要放在
()
里,只有当它们是标准的算术运算符(+
,-
,*
, &/
), 并且它们的优先级显而易见时,可以不用。When mixing operators, enclose them in parentheses. The only exception is the standard arithmetic operators:+
,-
, and**
since their precedence is broadly understood. We recommend enclosing/
and*
in parentheses because their precedence can be ambiguous when they are mixed. eslint:no-mixed-operators
Why? This improves readability and clarifies the developer's intention.
js// bad const foo = a && b < 0 || c > 0 || d + 1 === 0; // bad const bar = a ** b - 5 % d; // bad // one may be confused into thinking (a || b) && c if (a || b && c) { return d; } // bad const bar = a + b / c * d; // good const foo = (a && b < 0) || c > 0 || (d + 1 === 0); // good const bar = a ** b - (5 % d); // good if (a || (b && c)) { return d; } // good const bar = a + (b / c) * d;
-
15.9 无效合并运算符 (
??
) 是一个逻辑运算符,当其左侧操作数为null
或undefined
时,它返回其右侧操作数。否则,它将返回左侧操作数。The nullish coalescing operator (??
) is a logical operator that returns its right-hand side operand when its left-hand side operand isnull
orundefined
. Otherwise, it returns the left-hand side operand.Why? It provides precision by distinguishing null/undefined from other falsy values, enhancing code clarity and predictability.
js// bad const value = 0 ?? 'default'; // returns 0, not 'default' // bad const value = '' ?? 'default'; // returns '', not 'default' // good const value = null ?? 'default'; // returns 'default' // good const user = { name: 'John', age: null }; const age = user.age ?? 18; // returns 18
十六、块 (Blocks)
-
16.1 用大括号
{}
包裹多行代码块。Use braces with all multiline blocks. (eslint:nonblock-statement-body-position
)js// bad if (test) return false; // good if (test) return false; // good if (test) { return false; } // bad function foo() { return false; } // good function bar() { return false; }
-
16.2
else
和if
的大括号保持在一行。If you're using multiline blocks withif
andelse
, putelse
on the same line as yourif
block's closing brace. (eslint:brace-style
)js// bad if (test) { thing1(); thing2(); } else { thing3(); } // good if (test) { thing1(); thing2(); } else { thing3(); }
-
16.3 如果
if
语句都要用return
返回, 那后面的else
就不用写了。 如果if
块中包含return
, 它后面的else if
块中也包含了return
, 这个时候就可以把else if
拆开。 eslint:no-else-return
If anif
block always executes areturn
statement, the subsequentelse
block is unnecessary. Areturn
in anelse if
block following anif
block that contains areturn
can be separated into multipleif
blocks. eslint:no-else-return
js// bad function foo() { if (x) { return x; } else { return y; } } // bad function cats() { if (x) { return x; } else if (y) { return y; } } // bad function dogs() { if (x) { return x; } else { if (y) { return y; } } } // good function foo() { if (x) { return x; } return y; } // good function cats() { if (x) { return x; } if (y) { return y; } } // good function dogs(x) { if (x) { if (z) { return y; } } else { return z; } }
十七、控制语句 Control Statements
-
17.1 当你的控制语句
if
,while
等太长或者超过最大长度限制的时候,把每个判断条件放在单独一行里,逻辑运算符放在行首。In case your control statement (if
,while
etc.) gets too long or exceeds the maximum line length, each (grouped) condition could be put into a new line. The logical operator should begin the line.Why? Requiring operators at the beginning of the line keeps the operators aligned and follows a pattern similar to method chaining. This also improves readability by making it easier to visually follow complex logic.
js// bad if ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) { thing1(); } // bad if (foo === 123 && bar === 'abc') { thing1(); } // bad if (foo === 123 && bar === 'abc') { thing1(); } // bad if ( foo === 123 && bar === 'abc' ) { thing1(); } // good if ( foo === 123 && bar === 'abc' ) { thing1(); } // good if ( (foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening() ) { thing1(); } // good if (foo === 123 && bar === 'abc') { thing1(); }
-
17.2 不要用选择操作符代替控制语句。Don't use selection operators in place of control statements.
js// bad !isRunning && startRunning(); // good if (!isRunning) { startRunning(); }
十八、注释 Comments
-
18.1 多行注释用
/** ... */
。Use/** ... */
for multiline comments.js// bad // make() returns a new element // based on the passed in tag name // // @param {String} tag // @return {Element} element function make(tag) { // ... return element; } // good /** * make() returns a new element * based on the passed-in tag name */ function make(tag) { // ... return element; }
-
18.2 单行注释用
//
,将单行注释放在被注释区域上方。如果注释不是在第一行,就在注释前面加一个空行。Use//
for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it's on the first line of a block.js// bad const active = true; // is current tab // good // is current tab const active = true; // bad function getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this.type || 'no type'; return type; } // good function getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this.type || 'no type'; return type; } // also good function getType() { // set the default type to 'no type' const type = this.type || 'no type'; return type; }
-
18.3 所有注释开头加一个空格,方便阅读。Start all comments with a space to make it easier to read. *(eslint:
spaced-comment
)
js
// bad
//is current tab
const active = true;
// good
// is current tab
const active = true;
// bad
/**
*make() returns a new element
*based on the passed-in tag name
*/
function make(tag) {
// ...
return element;
}
// good
/**
* make() returns a new element
* based on the passed-in tag name
*/
function make(tag) {
// ...
return element;
}
- 18.4 在注释前加上
FIXME
或TODO
前缀, 这有助于其他开发人员快速理解你指出的问题, 或者您建议的问题的解决方案。Prefixing your comments withFIXME
orTODO
helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions areFIXME: -- need to figure this out
orTODO: -- need to implement
.
-
18.5 Use
// FIXME:
to annotate problems.jsclass Calculator extends Abacus { constructor() { super(); // FIXME: shouldn't use a global here total = 0; } }
-
18.6 Use
// TODO:
to annotate solutions to problems.jsclass Calculator extends Abacus { constructor() { super(); // TODO: total should be configurable by an options param this.total = 0; } }
十九、空格 Whitespace
-
19.1 Tab 使用两个空格
(或者 4 个,你开心就好,但是团队统一是必须的)。Use soft tabs (space character) set to 2 spaces. (eslint:indent
)csharp// bad function foo() { ∙∙∙∙let name; } // bad function bar() { ∙let name; } // good function baz() { ∙∙let name; }
-
19.2 在大括号
{}
前空一格。Place 1 space before the leading brace. eslint:space-before-blocks
js// bad function test(){ console.log('test'); } // good function test() { console.log('test'); } // bad dog.set('attr',{ age: '1 year', breed: 'Bernese Mountain Dog', }); // good dog.set('attr', { age: '1 year', breed: 'Bernese Mountain Dog', });
-
19.3 在控制语句
if
,while
等的圆括号前空一格。在函数调用和定义时,函数名和圆括号之间不空格。Place 1 space before the opening parenthesis in control statements (if
,while
etc.). Place no space between the argument list and the function name in function calls and declarations. eslint:keyword-spacing
js// bad if(isJedi) { fight (); } // good if (isJedi) { fight(); } // bad function fight () { console.log ('Swooosh!'); } // good function fight() { console.log('Swooosh!'); }
-
19.4 用空格来隔开运算符。Set off operators with spaces. eslint:
space-infix-ops
js// bad const x=y+5; // good const x = y + 5;
-
19.5 文件结尾空一行。End files with a single newline character. (eslint:
eol-last
) -
暂不采纳
js// bad import { es6 } from './AirbnbStyleGuide'; // ... export default es6; // bad import { es6 } from './AirbnbStyleGuide'; // ... export default es6;↵ ↵ // good import { es6 } from './AirbnbStyleGuide'; // ... export default es6;↵
-
19.6 当出现长的方法链(一般超过两个的时候)时换行。用点开头强调该行是一个方法调用,而不是一个新的语句。Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which emphasizes that the line is a method call, not a new statement. eslint:
newline-per-chained-call
no-whitespace-before-property
js// bad $('#items').find('.selected').highlight().end().find('.open').updateCount(); // bad $('#items'). find('.selected'). highlight(). end(). find('.open'). updateCount(); // good $('#items') .find('.selected') .highlight() .end() .find('.open') .updateCount(); // bad const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true) .attr('width', (radius + margin) * 2).append('svg:g') .attr('transform', `translate(${radius + margin}, ${radius + margin})`) .call(tron.led); // good const leds = stage.selectAll('.led') .data(data) .enter().append('svg:svg') .classed('led', true) .attr('width', (radius + margin) * 2) .append('svg:g') .attr('transform', `translate(${radius + margin}, ${radius + margin})`) .call(tron.led); // good const leds = stage.selectAll('.led').data(data); const svg = leds.enter().append('svg:svg'); svg.classed('led', true).attr('width', (radius + margin) * 2); const g = svg.append('svg:g'); g.attr('transform', `translate(${radius + margin}, ${radius + margin})`).call(tron.led);
-
19.7 在一个代码块之后,下一条语句之前空一行。Leave a blank line after blocks and before the next statement.
js// bad if (foo) { return bar; } return baz; // good if (foo) { return bar; } return baz; // bad const obj = { foo() { }, bar() { }, }; return obj; // good const obj = { foo() { }, bar() { }, }; return obj; // bad const arr = [ function foo() { }, function bar() { }, ]; return arr; // good const arr = [ function foo() { }, function bar() { }, ]; return arr;
-
19.8 不要故意留一些没必要的空白行。Do not pad your blocks with blank lines. eslint:
padded-blocks
js// bad function bar() { console.log(foo); } // bad if (baz) { console.log(quux); } else { console.log(foo); } // bad class Foo { constructor(bar) { this.bar = bar; } } // good function bar() { console.log(foo); } // good if (baz) { console.log(quux); } else { console.log(foo); }
-
19.9 不要加多行空格。Do not use multiple blank lines to pad your code. (eslint:
no-multiple-empty-lines
)js// bad class Person { constructor(fullName, email, birthday) { this.fullName = fullName; this.email = email; this.setAge(birthday); } setAge(birthday) { const today = new Date(); const age = this.getAge(today, birthday); this.age = age; } getAge(today, birthday) { // .. } } // good class Person { constructor(fullName, email, birthday) { this.fullName = fullName; this.email = email; this.setAge(birthday); } setAge(birthday) { const today = new Date(); const age = getAge(today, birthday); this.age = age; } getAge(today, birthday) { // .. } }
-
19.10 圆括号里不要加空格。Do not add spaces inside parentheses. (eslint:
space-in-parens
)js// bad function bar( foo ) { return foo; } // good function bar(foo) { return foo; } // bad if ( foo ) { console.log(foo); } // good if (foo) { console.log(foo); }
-
19.11 方括号里不要加空格。Do not add spaces inside brackets. (eslint:
array-bracket-spacing
)js// bad const foo = [ 1, 2, 3 ]; console.log(foo[ 0 ]); // good const foo = [1, 2, 3]; console.log(foo[0]);
-
19.12 花括号
{}
里加空格。Add spaces inside curly braces. eslint:object-curly-spacing
js// bad const foo = {clark: 'kent'}; // good const foo = { clark: 'kent' };
-
19.13 避免一行代码超过 100 个字符,需换行。(但包含空格、纯字符串就不要换行了)。Avoid having lines of code that are longer than 100 characters (including whitespace). Note: per above, long strings are exempt from this rule, and should not be broken up. eslint:
max-len
Why? This ensures readability and maintainability.
js// bad const foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy; // bad $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.')); // good const foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy; // better const foo = jsonData ?.foo ?.bar ?.baz ?.quux ?.xyzzy; // good $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' }, }) .done(() => console.log('Congratulations!')) .fail(() => console.log('You have failed this city.'));
-
19.14 同行间距一致。Require consistent spacing inside an open block token and the next token on the same line. This rule also enforces consistent spacing inside a close block token and previous token on the same line. (eslint:
block-spacing
)js// bad function foo() {return true;} if (foo) { bar = 0;} // good function foo() { return true; } if (foo) { bar = 0; }
-
19.15 逗号前避免使用空格,逗号后要求有空格。Avoid spaces before commas and require a space after commas. (eslint:
comma-spacing
)js// bad const foo = 1,bar = 2; const arr = [1 , 2]; // good const foo = 1, bar = 2; const arr = [1, 2];
-
19.16 在计算的属性括号内强制使用间距。Enforce spacing inside of computed property brackets. (eslint:
computed-property-spacing
)js// bad obj[foo ] obj[ 'foo'] const x = {[ b ]: a} obj[foo[ bar ]] // good obj[foo] obj['foo'] const x = { [b]: a } obj[foo[bar]]
-
19.17 避免在函数及其调用之间使用空格。Avoid spaces between functions and their invocations. eslint:
func-call-spacing
js// bad func (); func (); // good func();
-
19.18 在对象的属性中, 键和值之间要有空格。Enforce spacing between keys and values in object literal properties. eslint:
key-spacing
js// bad const obj = { foo : 42 }; const obj2 = { foo:42 }; // good const obj = { foo: 42 };
-
19.19 行末不要空格。Avoid trailing spaces at the end of lines. (eslint:
no-trailing-spaces
)
-
19.20 避免出现多个空行。 在文件末尾只允许空一行。Avoid multiple empty lines, only allow one newline at the end of files, and avoid a newline at the beginning of files. eslint:
no-multiple-empty-lines
js// bad - multiple empty lines const x = 1; const y = 2; // bad - 2+ newlines at end of file const x = 1; const y = 2; // bad - 1+ newline(s) at beginning of file const x = 1; const y = 2; // good const x = 1; const y = 2;
二十、逗号 Commas
-
20.1 不要前置逗号。Leading commas: Nope. (eslint:
comma-style
)js// bad const story = [ once , upon , aTime ]; // good const story = [ once, upon, aTime, ]; // bad const hero = { firstName: 'Ada' , lastName: 'Lovelace' , birthYear: 1815 , superPower: 'computers' }; // good const hero = { firstName: 'Ada', lastName: 'Lovelace', birthYear: 1815, superPower: 'computers', };
-
20.2 结尾额外加逗号Additional trailing comma: Yup. (eslint:
comma-dangle
)Why? This leads to cleaner git diffs. Also, transpilers like Babel will remove the additional trailing comma in the transpiled code which means you don't have to worry about the trailing comma problem in legacy browsers.
js// bad - git diff without trailing comma const hero = { firstName: 'Florence', - lastName: 'Nightingale' + lastName: 'Nightingale', + inventorOf: ['coxcomb chart', 'modern nursing'] }; // good - git diff with trailing comma const hero = { firstName: 'Florence', lastName: 'Nightingale', + inventorOf: ['coxcomb chart', 'modern nursing'], }; // bad const hero = { firstName: 'Dana', lastName: 'Scully' }; const heroes = [ 'Batman', 'Superman' ]; // good const hero = { firstName: 'Dana', lastName: 'Scully', }; const heroes = [ 'Batman', 'Superman', ]; // bad function createHero( firstName, lastName, inventorOf ) { // does nothing } // good function createHero( firstName, lastName, inventorOf, ) { // does nothing } // good (note that a comma must not appear after a "rest" element) function createHero( firstName, lastName, inventorOf, ...heroArgs ) { // does nothing } // bad createHero( firstName, lastName, inventorOf ); // good createHero( firstName, lastName, inventorOf, ); // good (note that a comma must not appear after a "rest" element) createHero( firstName, lastName, inventorOf, ...heroArgs );
二十一、分号 Semicolons
-
21.1 明确地使用分号。Yup. (eslint:
semi
)Why? When JavaScript encounters a line break without a semicolon, it uses a set of rules called Automatic Semicolon Insertion to determine whether it should regard that line break as the end of a statement, and (as the name implies) place a semicolon into your code before the line break if it thinks so. ASI contains a few eccentric behaviors, though, and your code will break if JavaScript misinterprets your line break. These rules will become more complicated as new features become a part of JavaScript. Explicitly terminating your statements and configuring your linter to catch missing semicolons will help prevent you from encountering issues.
为什么?当 JavaScript 遇到没有分号的换行符时,它会使用一组称为自动插入分号的规则来确定是否应该将该换行符视为语句的结尾,并且(顾名思义)在代码中放入分号之前,如果它认为是这样的话。但是,ASI 包含一些古怪的行为,如果 JavaScript 误解了换行符,您的代码就会中断。随着新功能成为 JavaScript 的一部分,这些规则将变得更加复杂。显式终止语句并配置 linter 以捕获缺少的分号将有助于防止遇到问题。
js// bad - raises exception const luke = {} const leia = {} [luke, leia].forEach((jedi) => jedi.father = 'vader') // bad - raises exception const reaction = "No! That's impossible!" (async function meanwhileOnTheFalcon() { // handle `leia`, `lando`, `chewie`, `r2`, `c3p0` // ... }()) // bad - returns `undefined` instead of the value on the next line - always happens when `return` is on a line by itself because of ASI! function foo() { return 'search your feelings, you know it to be foo' } // good const luke = {}; const leia = {}; [luke, leia].forEach((jedi) => { jedi.father = 'vader'; }); // good const reaction = 'No! That's impossible!'; (async function meanwhileOnTheFalcon() { // handle `leia`, `lando`, `chewie`, `r2`, `c3p0` // ... }()); // good function foo() { return 'search your feelings, you know it to be foo'; }