Airbnb JavaScript 风格指南() {

JavaScript最合理的方法 A mostly reasonable approach to JavaScript

注意: 这个指南假定你正在使用Babel, 并且需要你使用或等效的使用babel-preset-airbnb。 同时假定你在你的应用里安装了带有或等效的airbnb-browser-shimsshims/polyfills

Airbnb JavaScript 风格指南 - 图1
Airbnb JavaScript 风格指南 - 图2
Gitter

这个指南支持的其他语言翻译版请看 Translation

Other Style Guides

目录

  1. Types
  2. References
  3. Objects
  4. Arrays
  5. Destructuring
  6. Strings
  7. Functions
  8. Arrow Functions
  9. Classes & Constructors
  10. Modules
  11. Iterators and Generators
  12. Properties
  13. Variables
  14. Hoisting
  15. Comparison Operators & Equality
  16. Blocks
  17. Control Statements
  18. Comments
  19. Whitespace
  20. Commas
  21. Semicolons
  22. Type Casting & Coercion
  23. Naming Conventions
  24. Accessors
  25. Events
  26. jQuery
  27. ECMAScript 5 Compatibility
  28. ECMAScript 6+ (ES 2015+) Styles
  29. Standard Library
  30. Testing
  31. Performance
  32. Resources
  33. In the Wild
  34. Translation
  35. The JavaScript Style Guide Guide
  36. Chat With Us About JavaScript
  37. Contributors
  38. License
  39. Amendments

Types

  • 1.1 基本类型: 你可以直接获取到基本类型的值
    • string
    • number
    • boolean
    • null
    • undefined
    • symbol ```javascript const foo = 1; let bar = foo;

bar = 9;

console.log(foo, bar); // => 1, 9

  1. - Symbols 不能被正确的polyfill 所以在不能原生支持symbol类型的环境[浏览器]中,不应该使用 symbol 类型。
  2. - [1.2](#types--complex) 复杂类型: 复杂类型赋值是获取到他的引用的值。 相当于传引用
  3. - `object`
  4. - `array`
  5. - `function`
  6. ```javascript
  7. const foo = [1, 2];
  8. const bar = foo;
  9. bar[0] = 9;
  10. console.log(foo[0], bar[0]); // => 9, 9

⬆ back to top

References

  • 2.1 所有的赋值都用const,避免使用var. eslint: prefer-const, no-const-assign

    Why? 因为这个确保你不会改变你的初始值,重复引用会导致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. eslint: no-var

    Why? 因为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

⬆ back to top

Objects

  • 3.1 使用字面值创建对象. eslint: no-new-object ```javascript // bad const item = new Object();

// good const item = {};

  1. - [3.2](#es6-computed-properties) 当创建一个带有动态属性名的对象时,用计算后属性名
  2. > Why? 这可以使你将定义的所有属性放在对象的一个地方.
  3. ```javascript
  4. function getKey(k) {
  5. return `a key named ${k}`;
  6. }
  7. // bad
  8. const obj = {
  9. id: 5,
  10. name: 'San Francisco',
  11. };
  12. obj[getKey('enabled')] = true;
  13. // good getKey('enabled')是动态属性名
  14. const obj = {
  15. id: 5,
  16. name: 'San Francisco',
  17. [getKey('enabled')]: true,
  18. };
  • 3.3 用对象方法简写. 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; }, };

  1. - [3.4](#es6-object-concise) 用属性值缩写. eslint: [`object-shorthand`](http://eslint.org/docs/rules/object-shorthand.html)
  2. > Why? 这样写的更少且更可读
  3. ```javascript
  4. const lukeSkywalker = 'Luke Skywalker';
  5. // bad
  6. const obj = {
  7. lukeSkywalker: lukeSkywalker,
  8. };
  9. // good
  10. const obj = {
  11. lukeSkywalker,
  12. };
  • 3.5 将你的所有缩写放在对象声明的开始.

    Why? 这样也是为了更方便的知道有哪些属性用了缩写.

  1. const anakinSkywalker = 'Anakin Skywalker';
  2. const lukeSkywalker = 'Luke Skywalker';
  3. // bad
  4. const obj = {
  5. episodeOne: 1,
  6. twoJediWalkIntoACantina: 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. twoJediWalkIntoACantina: 2,
  18. episodeThree: 3,
  19. mayTheFourth: 4,
  20. };
  • 3.6 只对那些无效的标示使用引号 ''. eslint: quote-props

    Why? 通常我们认为这种方式主观上易读。他优化了代码高亮,并且页更容易被许多JS引擎压缩。

  1. // bad
  2. const bad = {
  3. 'foo': 3,
  4. 'bar': 4,
  5. 'data-blah': 5,
  6. };
  7. // good
  8. const good = {
  9. foo: 3,
  10. bar: 4,
  11. 'data-blah': 5,
  12. };
  • 3.7 不要直接调用Object.prototype上的方法,如hasOwnProperty, propertyIsEnumerable, isPrototypeOf

    Why? 在一些有问题的对象上, 这些方法可能会被屏蔽掉 - 如:{ hasOwnProperty: false } - 或这是一个空对象Object.create(null)

  1. // bad
  2. console.log(object.hasOwnProperty(key));
  3. // good
  4. console.log(Object.prototype.hasOwnProperty.call(object, key));
  5. // best
  6. const has = Object.prototype.hasOwnProperty; // 在模块作用内做一次缓存
  7. /* or */
  8. import has from 'has'; // https://www.npmjs.com/package/has
  9. // ...
  10. console.log(has.call(object, key));
  • 3.8 对象浅拷贝时,更推荐使用扩展运算符[就是...运算符],而不是Object.assign。获取对象指定的几个属性时,用对象的rest解构运算符[也是...运算符]更好。
    • 这一段不太好翻译出来, 大家看下面的例子就懂了。
  1. // very bad
  2. const original = { a: 1, b: 2 };
  3. const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ
  4. delete copy.a; // so does this
  5. // bad
  6. const original = { a: 1, b: 2 };
  7. const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }
  8. // good es6扩展运算符 ...
  9. const original = { a: 1, b: 2 };
  10. // 浅拷贝
  11. const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }
  12. // rest 赋值运算符
  13. const { a, ...noA } = copy; // noA => { b: 2, c: 3 }

⬆ back to top

Arrays

// good const items = [];

  1. - [4.2](#arrays--push) 用[Array#push](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push) 代替直接向数组中添加一个值。
  2. ```javascript
  3. const someStack = [];
  4. // bad
  5. someStack[someStack.length] = 'abracadabra';
  6. // good
  7. someStack.push('abracadabra');
  • 4.3 用扩展运算符做数组浅拷贝,类似上面的对象浅拷贝 ```javascript // bad const len = items.length; const itemsCopy = []; let i;

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

// good const itemsCopy = […items];

  1. - [4.4](#arrays--from-iterable) `...` 运算符而不是[`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from)来将一个可迭代的对象转换成数组。
  2. ```javascript
  3. const foo = document.querySelectorAll('.foo');
  4. // good
  5. const nodes = Array.from(foo);
  6. // best
  7. const nodes = [...foo];
  • 4.5Array.from 去将一个类数组对象转成一个数组。 ```javascript const arrLike = { 0: ‘foo’, 1: ‘bar’, 2: ‘baz’, length: 3 };

// bad const arr = Array.prototype.slice.call(arrLike);

// good const arr = Array.from(arrLike);

  1. - [4.6](#arrays--mapping) [`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from) 而不是 `...` 运算符去做map遍历。 因为这样可以避免创建一个临时数组。
  2. ```javascript
  3. // bad
  4. const baz = [...foo].map(bar);
  5. // good
  6. const baz = Array.from(foo, bar);
  • 4.7 在数组方法的回调函数中使用 return 语句。 如果函数体由一条返回一个表达式的语句组成, 并且这个表达式没有副作用, 这个时候可以忽略return,详见 8.2. eslint: array-callback-return ```javascript // good [1, 2, 3].map((x) => { const y = x + 1; return x * y; });

// good 函数只有一个语句 [1, 2, 3].map(x => x + 1);

// bad - 没有返回值, 因为在第一次迭代后acc 就变成undefined了 [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { const flatten = acc.concat(item); acc[index] = flatten; });

// good [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { const flatten = acc.concat(item); acc[index] = flatten; 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; });

  1. - [4.8](#arrays--bracket-newline) 如果一个数组有很多行,在数组的 `[` 后和 `]` 前断行。 请看下面示例
  2. ```javascript
  3. // bad
  4. const arr = [
  5. [0, 1], [2, 3], [4, 5],
  6. ];
  7. const objectInArray = [{
  8. id: 1,
  9. }, {
  10. id: 2,
  11. }];
  12. const numberInArray = [
  13. 1, 2,
  14. ];
  15. // good
  16. const arr = [[0, 1], [2, 3], [4, 5]];
  17. const objectInArray = [
  18. {
  19. id: 1,
  20. },
  21. {
  22. id: 2,
  23. },
  24. ];
  25. const numberInArray = [
  26. 1,
  27. 2,
  28. ];

⬆ back to top

Destructuring

  • 5.1 用对象的解构赋值来获取和使用对象某个或多个属性值。 eslint: prefer-destructuring

    Why? 解构保存了这些属性的临时值/引用

  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(user) {
  9. const { firstName, lastName } = user;
  10. return `${firstName} ${lastName}`;
  11. }
  12. // best
  13. function getFullName({ firstName, lastName }) {
  14. return `${firstName} ${lastName}`;
  15. }
  • 5.2 用数组解构. ```javascript const arr = [1, 2, 3, 4];

// bad const first = arr[0]; const second = arr[1];

// good const [first, second] = arr;

  1. - [5.3](#destructuring--object-over-array) 多个返回值用对象的解构,而不是数据解构。
  2. > Why? 你可以在后期添加新的属性或者变换变量的顺序而不会打破原有的调用
  3. ```javascript
  4. // bad
  5. function processInput(input) {
  6. // 然后就是见证奇迹的时刻
  7. return [left, right, top, bottom];
  8. }
  9. // 调用者需要想一想返回值的顺序
  10. const [left, __, top] = processInput(input);
  11. // good
  12. function processInput(input) {
  13. // oops, 奇迹又发生了
  14. return { left, right, top, bottom };
  15. }
  16. // 调用者只需要选择他想用的值就好了
  17. const { left, top } = processInput(input);

⬆ back to top

Strings

  • 6.1 对string用单引号 '' 。 eslint: quotes ```javascript // bad const name = “Capt. Janeway”;

// bad - 样例应该包含插入文字或换行 const name = Capt. Janeway;

// good const name = ‘Capt. Janeway’;

  1. - [6.2](#strings--line-length) 超过100个字符的字符串不应该用string串联成多行。
  2. > Why? 被折断的字符串工作起来是糟糕的而且使得代码更不易被搜索。
  3. ```javascript
  4. // bad
  5. const errorMessage = 'This is a super long error that was thrown because \
  6. of Batman. When you stop to think about how Batman had anything to do \
  7. with this, you would get nowhere \
  8. fast.';
  9. // bad
  10. const errorMessage = 'This is a super long error that was thrown because ' +
  11. 'of Batman. When you stop to think about how Batman had anything to do ' +
  12. 'with this, you would get nowhere fast.';
  13. // good
  14. 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 用字符串模板而不是字符串拼接来组织可编程字符串。 eslint: prefer-template template-curly-spacing

    Why? 模板字符串更具可读性、语法简洁、字符串插入参数。

  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. // bad
  10. function sayHi(name) {
  11. return `How are you, ${ name }?`;
  12. }
  13. // good
  14. function sayHi(name) {
  15. return `How are you, ${name}?`;
  16. }
  • 6.4 永远不要在字符串中用eval(),他就是潘多拉盒子。 eslint: no-eval
  • 6.5 不要使用不必要的转义字符。eslint: no-useless-escape

    Why? 反斜线可读性差,所以他们只在必须使用时才出现哦

  1. // bad
  2. const foo = '\'this\' \i\s \"quoted\"';
  3. // good
  4. const foo = '\'this\' is "quoted"';
  5. //best
  6. const foo = `my name is '${name}'`;

⬆ back to top

Functions

  • 7.1 用命名函数表达式而不是函数声明。eslint: func-style

    函数表达式: const func = function () {} 函数声明: function func() {} Why? 函数声明时作用域被提前了,这意味着在一个文件里函数很容易(太容易了)在其定义之前被引用。这样伤害了代码可读性和可维护性。如果你发现一个函数有大又复杂,这个函数妨碍这个文件其他部分的理解性,这可能就是时候把这个函数单独抽成一个模块了。别忘了给表达式显示的命名,不用管这个名字是不是由一个确定的变量推断出来的,这消除了由匿名函数在错误调用栈产生的所有假设,这在现代浏览器和类似babel编译器中很常见 (Discussion) Why? 这一段还不理解这种错误发生的场景,所以只能直译过来了, 另附原文 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)

  1. // bad
  2. function foo() {
  3. // ...
  4. }
  5. // bad
  6. const foo = function () {
  7. // ...
  8. };
  9. // good
  10. // lexical name distinguished from the variable-referenced invocation(s)
  11. // 函数表达式名和声明的函数名是不一样的
  12. const short = function longUniqueMoreDescriptiveLexicalFoo() {
  13. // ...
  14. };
  • 7.2 把立即执行函数包裹在圆括号里。 eslint: wrap-iife

    Why? immediately invoked function expression = IIFE Why? 一个立即调用的函数表达式是一个单元 - 把它和他的调用者(圆括号)包裹起来,在括号中可以清晰的地表达这些。 Why? 注意:在模块化世界里,你几乎用不着 IIFE

  1. // immediately-invoked function expression (IIFE)
  2. (function () {
  3. console.log('Welcome to the Internet. Please follow me.');
  4. }());
  • 7.3 不要在非函数块(if、while等等)内声明函数。把这个函数分配给一个变量。浏览器会允许你这样做,但浏览器解析方式不同,这是一个坏消息。【详见no-loop-func】 eslint: no-loop-func
  • 7.4 Note: 在ECMA-262中 [块 block] 的定义是: 一系列的语句; 但是函数声明不是一个语句。 函数表达式是一个语句。 ```javascript // bad if (currentUser) { function test() { console.log(‘Nope.’); } }

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

  1. - [7.5](#functions--arguments-shadow) 不要用`arguments`命名参数。他的优先级高于每个函数作用域自带的 `arguments` 对象, 这会导致函数自带的 `arguments` 值被覆盖
  2. ```javascript
  3. // bad
  4. function foo(name, options, arguments) {
  5. // ...
  6. }
  7. // good
  8. function foo(name, options, args) {
  9. // ...
  10. }
  • 7.6 不要使用arguments,用rest语法...代替。 eslint: prefer-rest-params

    Why? ...明确你想用那个参数。而且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 用默认参数语法而不是在函数里对参数重新赋值。 ```javascript // really bad function handleThings(opts) { // 不, 我们不该改arguments // 第二: 如果 opts 的值为 false, 它会被赋值为 {} // 虽然你想这么写, 但是这个会带来一些细微的bug opts = opts || {}; // … }

// still bad function handleThings(opts) { if (opts === void 0) { opts = {}; } // … }

// good function handleThings(opts = {}) { // … }

  1. - [7.8](#functions--default-side-effects) 默认参数避免副作用
  2. > Why? 他会令人迷惑不解, 比如下面这个, a到底等于几, 这个需要想一下。
  3. ```javascript
  4. var b = 1;
  5. // bad
  6. function count(a = b++) {
  7. console.log(a);
  8. }
  9. count(); // 1
  10. count(); // 2
  11. count(3); // 3
  12. count(); // 3
  • 7.9 把默认参数赋值放在最后 ```javascript // bad function handleThings(opts = {}, name) { // … }

// good function handleThings(name, opts = {}) { // … }

  1. - [7.10](#functions--constructor) 不要用函数构造器创建函数。 eslint: [`no-new-func`](http://eslint.org/docs/rules/no-new-func)
  2. > Why? 以这种方式创建函数将类似于字符串 eval(),这会打开漏洞。
  3. ```javascript
  4. // bad
  5. var add = new Function('a', 'b', 'return a + b');
  6. // still bad
  7. var subtract = Function('a', 'b', 'return a - b');
  1. // bad
  2. const f = function(){};
  3. const g = function (){};
  4. const h = function() {};
  5. // good
  6. const x = function () {};
  7. const y = function a() {};
  • 7.12 不要改参数. eslint: no-param-reassign

    Why? 操作参数对象对原始调用者会导致意想不到的副作用。 就是不要改参数的数据结构,保留参数原始值和数据结构。

  1. // bad
  2. function f1(obj) {
  3. obj.key = 1;
  4. };
  5. // good
  6. function f2(obj) {
  7. const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;
  8. };
  • 7.13 不要对参数重新赋值。 eslint: no-param-reassign

    Why? 参数重新赋值会导致意外行为,尤其是对 arguments。这也会导致优化问题,特别是在V8里

  1. // bad
  2. function f1(a) {
  3. a = 1;
  4. // ...
  5. }
  6. function f2(a) {
  7. if (!a) { a = 1; }
  8. // ...
  9. }
  10. // good
  11. function f3(a) {
  12. const b = a || 1;
  13. // ...
  14. }
  15. function f4(a = 1) {
  16. // ...
  17. }
  • 7.14spread操作符...去调用多变的函数更好。 eslint: prefer-spread

    Why? 这样更清晰,你不必提供上下文,而且你不能轻易地用apply来组成new

  1. // bad
  2. const x = [1, 2, 3, 4, 5];
  3. console.log.apply(console, x);
  4. // good
  5. const x = [1, 2, 3, 4, 5];
  6. console.log(...x);
  7. // bad
  8. new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5]));
  9. // good
  10. new Date(...[2016, 8, 5]);
  • 7.15 调用或者书写一个包含多个参数的函数应该像这个指南里的其他多行代码写法一样: 每行值包含一个参数,每行逗号结尾。 ```javascript // bad function foo(bar,
    1. baz,
    2. quux) {
    // … }

// good 缩进不要太过分 function foo( bar, baz, quux, ) { // … }

// bad console.log(foo, bar, baz);

// good console.log( foo, bar, baz, );

  1. **[⬆ back to top](#%E7%9B%AE%E5%BD%95)**
  2. <a name="889bffd0"></a>
  3. ## Arrow Functions
  4. - [8.1](#arrows--use-them) 当你一定要用函数表达式(在回调函数里)的时候就用箭头表达式吧。 eslint: [`prefer-arrow-callback`](http://eslint.org/docs/rules/prefer-arrow-callback.html), [`arrow-spacing`](http://eslint.org/docs/rules/arrow-spacing.html)
  5. > Why? 他创建了一个`this`的当前执行上下文的函数的版本,这通常就是你想要的;而且箭头函数是更简洁的语法
  6. > Why? 什么时候不用箭头函数: 如果你有一个相当复杂的函数,你可能会把这个逻辑移出到他自己的函数声明里。
  7. ```javascript
  8. // bad
  9. [1, 2, 3].map(function (x) {
  10. const y = x + 1;
  11. return x * y;
  12. });
  13. // good
  14. [1, 2, 3].map((x) => {
  15. const y = x + 1;
  16. return x * y;
  17. });
  • 8.2 如果函数体由一个没有副作用的表达式语句组成,删除大括号和return。否则,继续用大括号和 return 语句。 eslint: arrow-parens, arrow-body-style

    Why? 语法糖,当多个函数链在一起的时候好读

  1. // bad
  2. [1, 2, 3].map(number => {
  3. const nextNumber = number + 1;
  4. `A string containing the ${nextNumber}.`;
  5. });
  6. // good
  7. [1, 2, 3].map(number => `A string containing the ${number}.`);
  8. // good
  9. [1, 2, 3].map((number) => {
  10. const nextNumber = number + 1;
  11. return `A string containing the ${nextNumber}.`;
  12. });
  13. // good
  14. [1, 2, 3].map((number, index) => ({
  15. [index]: number
  16. }));
  17. // 表达式有副作用就不要用隐式return
  18. function foo(callback) {
  19. const val = callback();
  20. if (val === true) {
  21. // Do something if callback returns true
  22. }
  23. }
  24. let bool = false;
  25. // bad
  26. // 这种情况会return bool = true, 不好
  27. foo(() => bool = true);
  28. // good
  29. foo(() => {
  30. bool = true;
  31. });
  • 8.3 万一表达式涉及多行,把他包裹在圆括号里更可读。

    Why? 这样清晰的显示函数的开始和结束

  1. // bad
  2. ['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call(
  3. httpMagicObjectWithAVeryLongName,
  4. httpMethod
  5. )
  6. );
  7. // good
  8. ['get', 'post', 'put'].map(httpMethod => (
  9. Object.prototype.hasOwnProperty.call(
  10. httpMagicObjectWithAVeryLongName,
  11. httpMethod
  12. )
  13. ));
  • 8.4 如果你的函数只有一个参数并且函数体没有大括号,就删除圆括号。否则,参数总是放在圆括号里。 注意: 一直用圆括号也是没问题,只需要配置 “always” option for eslint. eslint: arrow-parens

    Why? 这样少一些混乱, 其实没啥语法上的讲究,就保持一个风格。

  1. // bad
  2. [1, 2, 3].map((x) => x * x);
  3. // good
  4. [1, 2, 3].map(x => x * x);
  5. // good
  6. [1, 2, 3].map(number => (
  7. `A long string with the ${number}. Its so long that we dont want it to take up space on the .map line!`
  8. ));
  9. // bad
  10. [1, 2, 3].map(x => {
  11. const y = x + 1;
  12. return x * y;
  13. });
  14. // good
  15. [1, 2, 3].map((x) => {
  16. const y = x + 1;
  17. return x * y;
  18. });
  • 8.5 避免箭头函数(=>)和比较操作符(<=, >=)混淆. eslint: no-confusing-arrow ```javascript // 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; };

  1. - [8.6](#whitespace--implicit-arrow-linebreak) 在隐式return中强制约束函数体的位置, 就写在箭头后面。 eslint: [`implicit-arrow-linebreak`](https://eslint.org/docs/rules/implicit-arrow-linebreak)
  2. ```javascript
  3. // bad
  4. (foo) =>
  5. bar;
  6. (foo) =>
  7. (bar);
  8. // good
  9. (foo) => bar;
  10. (foo) => (bar);
  11. (foo) => (
  12. bar
  13. )

⬆ back to top

Classes & Constructors

  • 9.1 常用class,避免直接操作prototype

    Why? class语法更简洁更易理解

  1. // bad
  2. function Queue(contents = []) {
  3. this.queue = [...contents];
  4. }
  5. Queue.prototype.pop = function () {
  6. const value = this.queue[0];
  7. this.queue.splice(0, 1);
  8. return value;
  9. };
  10. // good
  11. class Queue {
  12. constructor(contents = []) {
  13. this.queue = [...contents];
  14. }
  15. pop() {
  16. const value = this.queue[0];
  17. this.queue.splice(0, 1);
  18. return value;
  19. }
  20. }
  • 9.2extends实现继承

    Why? 它是一种内置的方法来继承原型功能而不打破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来实现方法链 ```javascript // 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);

  1. - [9.4](#constructors--tostring) 写一个定制的toString()方法是可以的,只要保证它是可以正常工作且没有副作用的
  2. ```javascript
  3. class Jedi {
  4. constructor(options = {}) {
  5. this.name = options.name || 'no name';
  6. }
  7. getName() {
  8. return this.name;
  9. }
  10. toString() {
  11. return `Jedi - ${this.getName()}`;
  12. }
  13. }
  • 9.5 如果没有具体说明,类有默认的构造方法。一个空的构造函数或只是代表父类的构造函数是不需要写的。 eslint: no-useless-constructor ```javascript // 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’; } }

  1. - [9.6](#classes--no-duplicate-members) 避免重复类成员。 eslint: [`no-dupe-class-members`](http://eslint.org/docs/rules/no-dupe-class-members)
  2. > Why? 重复类成员会默默的执行最后一个 —— 重复本身也是一个bug
  3. ```javascript
  4. // bad
  5. class Foo {
  6. bar() { return 1; }
  7. bar() { return 2; }
  8. }
  9. // good
  10. class Foo {
  11. bar() { return 1; }
  12. }
  13. // good
  14. class Foo {
  15. bar() { return 2; }
  16. }

⬆ back to top

Modules

  • 10.1 用(import/export) 模块而不是无标准的模块系统。你可以随时转到你喜欢的模块系统。

    Why? 模块化是未来,让我们现在就开启未来吧。

  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通配符, 就是 * 这种方式

    Why? 这确保你有单个默认的导出

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

    Why? 虽然一行是简洁的,有一个明确的方式进口和一个明确的出口方式来保证一致性。

  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;
  • 10.4 一个路径只 import 一次。
    eslint: no-duplicate-imports

    Why? 从同一个路径下import多行会使代码难以维护

  1. // bad
  2. import foo from 'foo';
  3. // … some other imports … //
  4. import { named1, named2 } from 'foo';
  5. // good
  6. import foo, { named1, named2 } from 'foo';
  7. // good
  8. import foo, {
  9. named1,
  10. named2,
  11. } from 'foo';
  • 10.5 不要到处可变的东西
    eslint: import/no-mutable-exports

    Why? 变化通常都是需要避免,特别是当你要输出可变的绑定。虽然在某些场景下可能需要这种技术,但总的来说应该导出常量。

  1. // bad
  2. let foo = 3;
  3. export { foo }
  4. // good
  5. const foo = 3;
  6. export { foo }
  • 10.6 在一个单一导出模块里,用 export default 更好。
    eslint: import/prefer-default-export

    Why? 鼓励使用更多文件,每个文件只做一件事情并导出,这样可读性和可维护性更好。

  1. // bad
  2. export function foo() {}
  3. // good
  4. export default function foo() {}
  • 10.7 import 放在其他所有语句之前。
    eslint: import/first

    Why? 让import放在最前面防止意外行为。

  1. // bad
  2. import foo from 'foo';
  3. foo.init();
  4. import bar from 'bar';
  5. // good
  6. import foo from 'foo';
  7. import bar from 'bar';
  8. foo.init();
  • 10.8 多行import应该缩进,就像多行数组和对象字面量

    Why? 花括号与样式指南中每个其他花括号块遵循相同的缩进规则,逗号也是。

  1. // bad
  2. import {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path';
  3. // good
  4. import {
  5. longNameA,
  6. longNameB,
  7. longNameC,
  8. longNameD,
  9. longNameE,
  10. } from 'path';
  • 10.9 在import语句里不允许Webpack loader语法
    eslint: import/no-webpack-loader-syntax

    Why? 一旦用Webpack语法在import里会把代码耦合到模块绑定器。最好是在webpack.config.js里写webpack loader语法

  1. // bad
  2. import fooSass from 'css!sass!foo.scss';
  3. import barCss from 'style!css!bar.css';
  4. // good
  5. import fooSass from 'foo.scss';
  6. import barCss from 'bar.css';

⬆ back to top

Iterators and Generators

  • 11.1 不要用遍历器。用JavaScript高级函数代替for-infor-of。 eslint: no-iterator no-restricted-syntax

    Why? 这强调了我们不可变的规则。 处理返回值的纯函数比副作用更容易。 Why? 用数组的这些迭代方法: map() / every() / filter() / find() / findIndex() / reduce() / some() / … , 用对象的这些方法 Object.keys() / Object.values() / Object.entries() 去产生一个数组, 这样你就能去遍历对象了。

  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;
  15. // bad
  16. const increasedByOne = [];
  17. for (let i = 0; i < numbers.length; i++) {
  18. increasedByOne.push(numbers[i] + 1);
  19. }
  20. // good
  21. const increasedByOne = [];
  22. numbers.forEach(num => increasedByOne.push(num + 1));
  23. // best (keeping it functional)
  24. const increasedByOne = numbers.map(num => num + 1);
  • 11.2 现在不要用generator

    Why? 它在es5上支持的不好

  • 11.3 如果你一定要用,或者你忽略我们的建议, 请确保它们的函数签名空格是得当的。 eslint: generator-star-spacing

    Why? function* 是同一概念关键字 - *不是function的修饰符,function*是一个和function不一样的独特结构

  1. // bad
  2. function * foo() {
  3. // ...
  4. }
  5. // bad
  6. const bar = function * () {
  7. // ...
  8. }
  9. // bad
  10. const baz = function *() {
  11. // ...
  12. }
  13. // bad
  14. const quux = function*() {
  15. // ...
  16. }
  17. // bad
  18. function*foo() {
  19. // ...
  20. }
  21. // bad
  22. function *foo() {
  23. // ...
  24. }
  25. // very bad
  26. function
  27. *
  28. foo() {
  29. // ...
  30. }
  31. // very bad
  32. const wat = function
  33. *
  34. () {
  35. // ...
  36. }
  37. // good
  38. function* foo() {
  39. // ...
  40. }
  41. // good
  42. const foo = function* () {
  43. // ...
  44. }

⬆ back to top

Properties

  • 12.1 访问属性时使用点符号. eslint: dot-notation ```javascript const luke = { jedi: true, age: 28, };

// bad const isJedi = luke[‘jedi’];

// good const isJedi = luke.jedi;

  1. - [12.2](#properties--bracket) 当获取的属性是变量时用方括号`[]`
  2. ```javascript
  3. const luke = {
  4. jedi: true,
  5. age: 28,
  6. };
  7. function getProp(prop) {
  8. return luke[prop];
  9. }
  10. const isJedi = getProp('jedi');

// good const binary = 2 ** 10;

  1. **[⬆ back to top](#%E7%9B%AE%E5%BD%95)**
  2. <a name="Variables"></a>
  3. ## Variables
  4. - [13.1](#variables--const) `const``let`声明变量。不这样做会导致全局变量。 我们想要避免污染全局命名空间。首长这样警告我们。 eslint: [`no-undef`](http://eslint.org/docs/rules/no-undef) [`prefer-const`](http://eslint.org/docs/rules/prefer-const)
  5. ```javascript
  6. // bad
  7. superPower = new SuperPower();
  8. // good
  9. const superPower = new SuperPower();
  • 13.2 每个变量都用一个 constlet。 eslint: one-var

    Why? 这种方式很容易去声明新的变量,你不用去考虑把;调换成,,或者引入一个只有标点的不同的变化。这种做法也可以是你在调试的时候单步每个声明语句,而不是一下跳过所有声明。

  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 const放一起,let放一起

    Why? 在你需要分配一个新的变量, 而这个变量依赖之前分配过的变量的时候,这种做法是有帮助的

  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 在你需要的地方声明变量,但是要放在合理的位置

    Why? letconst 都是块级作用域而不是函数级作用域

  1. // bad - unnecessary function call
  2. function checkName(hasName) {
  3. const name = getName();
  4. if (hasName === 'test') {
  5. return false;
  6. }
  7. if (name === 'test') {
  8. this.setName('');
  9. return false;
  10. }
  11. return name;
  12. }
  13. // good
  14. function checkName(hasName) {
  15. if (hasName === 'test') {
  16. return false;
  17. }
  18. // 在需要的时候分配
  19. const name = getName();
  20. if (name === 'test') {
  21. this.setName('');
  22. return false;
  23. }
  24. return name;
  25. }
  • 13.5 不要使用链接变量分配。 eslint: no-multi-assign

    Why? 链接变量分配创建隐式全局变量。

  1. // bad
  2. (function example() {
  3. // JavaScript 将这一段解释为
  4. // let a = ( b = ( c = 1 ) );
  5. // let 只对变量 a 起作用; 变量 b 和 c 都变成了全局变量
  6. let a = b = c = 1;
  7. }());
  8. console.log(a); // undefined
  9. console.log(b); // 1
  10. console.log(c); // 1
  11. // good
  12. (function example() {
  13. let a = 1;
  14. let b = a;
  15. let c = a;
  16. }());
  17. console.log(a); // undefined
  18. console.log(b); // undefined
  19. console.log(c); // undefined
  20. // `const` 也是如此
  • 13.6 不要使用一元自增自减运算符(++--). eslint no-plusplus

    Why? 根据eslint文档,一元增量和减量语句受到自动分号插入的影响,并且可能会导致应用程序中的值递增或递减的无声错误。 使用num + = 1而不是num ++num ++语句来表达你的值也是更有表现力的。 禁止一元增量和减量语句还会阻止您无意地预增/预减值,这也会导致程序出现意外行为。

  1. // bad
  2. let array = [1, 2, 3];
  3. let num = 1;
  4. num++;
  5. --num;
  6. let sum = 0;
  7. let truthyCount = 0;
  8. for(let i = 0; i < array.length; i++){
  9. let value = array[i];
  10. sum += value;
  11. if (value) {
  12. truthyCount++;
  13. }
  14. }
  15. // good
  16. let array = [1, 2, 3];
  17. let num = 1;
  18. num += 1;
  19. num -= 1;
  20. const sum = array.reduce((a, b) => a + b, 0);
  21. const truthyCount = array.filter(Boolean).length;
  • 13.7 在赋值的时候避免在 = 前/后换行。 如果你的赋值语句超出 max-len, 那就用小括号把这个值包起来再换行。 eslint operator-linebreak.

    Why? 在 = 附近换行容易混淆这个赋值语句。

  1. // bad
  2. const foo =
  3. superLongLongLongLongLongLongLongLongFunctionName();
  4. // bad
  5. const foo
  6. = 'superLongLongLongLongLongLongLongLongString';
  7. // good
  8. const foo = (
  9. superLongLongLongLongLongLongLongLongFunctionName()
  10. );
  11. // good
  12. const foo = 'superLongLongLongLongLongLongLongLongString';
  • 13.8 不允许有未使用的变量。 eslint: no-unused-vars

    Why? 一个声明了但未使用的变量更像是由于重构未完成产生的错误。这种在代码中出现的变量会使阅读者迷惑。

  1. // bad
  2. var some_unused_var = 42;
  3. // 写了没用
  4. var y = 10;
  5. y = 5;
  6. // 变量改了自己的值,也没有用这个变量
  7. var z = 0;
  8. z = z + 1;
  9. // 参数定义了但未使用
  10. function getX(x, y) {
  11. return x;
  12. }
  13. // good
  14. function getXPlusY(x, y) {
  15. return x + y;
  16. }
  17. var x = 1;
  18. var y = a + 2;
  19. alert(getXPlusY(x, y));
  20. // 'type' 即使没有使用也可以可以被忽略, 因为这个有一个 rest 取值的属性。
  21. // 这是从对象中抽取一个忽略特殊字段的对象的一种形式
  22. var { type, ...coords } = data;
  23. // 'coords' 现在就是一个没有 'type' 属性的 'data' 对象

⬆ back to top

Hoisting

  • 14.1 var声明会被提前到他的作用域的最前面,它分配的值还没有提前。constlet被赋予了新的调用概念时效区 —— Temporal Dead Zones (TDZ)。 重要的是要知道为什么 typeof不再安全. ```javascript // 我们知道这个不会工作,假设没有定义全局的notDefined function example() { console.log(notDefined); // => throws a ReferenceError }

// 在你引用的地方之后声明一个变量,他会正常输出是因为变量作用域上升。 // 注意: declaredButNotAssigned的值没有上升 function example() { console.log(declaredButNotAssigned); // => undefined var declaredButNotAssigned = true; }

// 解释器把变量声明提升到作用域最前面, // 可以重写成如下例子, 二者意义相同 function example() { let declaredButNotAssigned; console.log(declaredButNotAssigned); // => undefined declaredButNotAssigned = true; }

// 用 const, let就不一样了 function example() { console.log(declaredButNotAssigned); // => throws a ReferenceError console.log(typeof declaredButNotAssigned); // => throws a ReferenceError const declaredButNotAssigned = true; }

  1. - [14.2](#hoisting--anon-expressions) 匿名函数表达式和 `var` 情况相同
  2. ```javascript
  3. function example() {
  4. console.log(anonymous); // => undefined
  5. anonymous(); // => TypeError anonymous is not a function
  6. var anonymous = function () {
  7. console.log('anonymous function expression');
  8. };
  9. }
  • 14.3 已命名函数表达式提升他的变量名,不是函数名或函数体 ```javascript function 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’); }; }

// 函数名和变量名一样是也如此 function example() { console.log(named); // => undefined

named(); // => TypeError named is not a function

var named = function named() { console.log(‘named’); }; }

  1. - [14.4](#hoisting--declarations) 函数声明则提升了函数名和函数体
  2. ```javascript
  3. function example() {
  4. superPower(); // => Flying
  5. function superPower() {
  6. console.log('Flying');
  7. }
  8. }

⬆ back to top

Comparison Operators & Equality

  • 15.1===!== 而不是 ==!=. eslint: eqeqeq
  • 15.2 条件语句如’if’语句使用强制`ToBoolean’抽象方法来评估它们的表达式,并且始终遵循以下简单规则:
    • Objects 计算成 true
    • Undefined 计算成 false
    • Null 计算成 false
    • Booleans 计算成 the value of the boolean
    • Numbers
      • +0, -0, or NaN 计算成 false
      • 其他 true
    • Strings
      • '' 计算成 false
      • 其他 true
        1. if ([0] && []) {
        2. // true
        3. // 数组(即使是空数组)是对象,对象会计算成true
        4. }
  • 15.3 布尔值用缩写,而字符串和数字要明确比较对象 ```javascript // bad if (isValid === true) { // … }

// good if (isValid) { // … }

// bad if (name) { // … }

// good if (name !== ‘’) { // … }

// bad if (collection.length) { // … }

// good if (collection.length > 0) { // … }

  1. - [15.4](#comparison--moreinfo) 更多信息请见Angus Croll的[真理、平等和JavaScript —— Truth Equality and JavaScript](https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108)
  2. - [15.5](#comparison--switch-blocks) `case``default`分句里用大括号创建一块包含语法声明的区域(e.g. `let`, `const`, `function`, and `class`). eslint rules: [`no-case-declarations`](http://eslint.org/docs/rules/no-case-declarations.html).
  3. > Why? 语法声明在整个`switch`的代码块里都可见,但是只有当其被分配后才会初始化,他的初始化时当这个`case`被执行时才产生。 当多个`case`分句试图定义同一个事情时就出问题了
  4. ```javascript
  5. // bad
  6. switch (foo) {
  7. case 1:
  8. let x = 1;
  9. break;
  10. case 2:
  11. const y = 2;
  12. break;
  13. case 3:
  14. function f() {
  15. // ...
  16. }
  17. break;
  18. default:
  19. class C {}
  20. }
  21. // good
  22. switch (foo) {
  23. case 1: {
  24. let x = 1;
  25. break;
  26. }
  27. case 2: {
  28. const y = 2;
  29. break;
  30. }
  31. case 3: {
  32. function f() {
  33. // ...
  34. }
  35. break;
  36. }
  37. case 4:
  38. bar();
  39. break;
  40. default: {
  41. class C {}
  42. }
  43. }
  • 15.6 三元表达式不应该嵌套,通常是单行表达式。
    eslint rules: no-nested-ternary. ```javascript // bad const foo = maybe1 > maybe2 ? “bar” : value1 > value2 ? “baz” : null;

// better const maybeNull = value1 > value2 ? ‘baz’ : null;

const foo = maybe1 > maybe2 ? ‘bar’ : maybeNull;

// best const maybeNull = value1 > value2 ? ‘baz’ : null;

const foo = maybe1 > maybe2 ? ‘bar’ : maybeNull;

  1. - [15.7](#comparison--unneeded-ternary) 避免不需要的三元表达式
  2. <br />eslint rules: [`no-unneeded-ternary`](http://eslint.org/docs/rules/no-unneeded-ternary.html).
  3. ```javascript
  4. // bad
  5. const foo = a ? a : b;
  6. const bar = c ? true : false;
  7. const baz = c ? false : true;
  8. // good
  9. const foo = a || b;
  10. const bar = !!c;
  11. const baz = !c;
  • 15.8 用圆括号来混合这些操作符。 只有当标准的算术运算符(+, -, *, & /), 并且它们的优先级显而易见时,可以不用圆括号括起来。 eslint: no-mixed-operators

    Why? 这提高了可读性,并且明确了开发者的意图

  1. // bad
  2. const foo = a && b < 0 || c > 0 || d + 1 === 0;
  3. // bad
  4. const bar = a ** b - 5 % d;
  5. // bad
  6. // 别人会陷入(a || b) && c 的迷惑中
  7. if (a || b && c) {
  8. return d;
  9. }
  10. // good
  11. const foo = (a && b < 0) || c > 0 || (d + 1 === 0);
  12. // good
  13. const bar = (a ** b) - (5 % d);
  14. // good
  15. if (a || (b && c)) {
  16. return d;
  17. }
  18. // good
  19. const bar = a + b / c * d;

⬆ back to top

Blocks

// good if (test) return false;

// good if (test) { return false; }

// bad function foo() { return false; }

// good function bar() { return false; }

  1. - [16.2](#blocks--cuddled-elses) `if`表达式的`else``if`的关闭大括号在一行。 eslint: [`brace-style`](http://eslint.org/docs/rules/brace-style.html)
  2. ```javascript
  3. // bad
  4. if (test) {
  5. thing1();
  6. thing2();
  7. }
  8. else {
  9. thing3();
  10. }
  11. // good
  12. if (test) {
  13. thing1();
  14. thing2();
  15. } else {
  16. thing3();
  17. }
  • 16.3 如果 if 语句中总是需要用 return 返回, 那后续的 else 就不需要写了。 if 块中包含 return, 它后面的 else if 块中也包含了 return, 这个时候就可以把 return 分到多个 if 语句块中。 eslint: no-else-return ```javascript // 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; } }

  1. **[⬆ back to top](#%E7%9B%AE%E5%BD%95)**
  2. <a name="7e064c85"></a>
  3. ## Control Statements
  4. - [17.1](#control-statements) 当你的控制语句(`if`, `while` 等)太长或者超过最大长度限制的时候, 把每一个(组)判断条件放在单独一行里。 逻辑操作符放在行首。
  5. > Why? 把逻辑操作符放在行首是让操作符的对齐方式和链式函数保持一致。这提高了可读性,也让复杂逻辑更容易看清楚。
  6. ```javascript
  7. // bad
  8. if ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) {
  9. thing1();
  10. }
  11. // bad
  12. if (foo === 123 &&
  13. bar === 'abc') {
  14. thing1();
  15. }
  16. // bad
  17. if (foo === 123
  18. && bar === 'abc') {
  19. thing1();
  20. }
  21. // bad
  22. if (
  23. foo === 123 &&
  24. bar === 'abc'
  25. ) {
  26. thing1();
  27. }
  28. // good
  29. if (
  30. foo === 123
  31. && bar === 'abc'
  32. ) {
  33. thing1();
  34. }
  35. // good
  36. if (
  37. (foo === 123 || bar === 'abc')
  38. && doesItLookGoodWhenItBecomesThatLong()
  39. && isThisReallyHappening()
  40. ) {
  41. thing1();
  42. }
  43. // good
  44. if (foo === 123 && bar === 'abc') {
  45. thing1();
  46. }
  • 17.2 不要用选择操作符代替控制语句。 ```javascript // bad !isRunning && startRunning();

// good if (!isRunning) { startRunning(); }

  1. **[⬆ back to top](#table-of-contents)**
  2. <a name="Comments"></a>
  3. ## Comments
  4. - [18.1](#comments--multiline) 多行注释用 `/** ... */`
  5. ```javascript
  6. // bad
  7. // make() returns a new element
  8. // based on the passed in tag name
  9. //
  10. // @param {String} tag
  11. // @return {Element} element
  12. function make(tag) {
  13. // ...
  14. return element;
  15. }
  16. // good
  17. /**
  18. * make() returns a new element
  19. * based on the passed-in tag name
  20. */
  21. function make(tag) {
  22. // ...
  23. return element;
  24. }
  • 18.2 单行注释用//,将单行注释放在被注释区域上面。如果注释不是在第一行,那么注释前面就空一行 ```javascript // 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; }

  1. - [18.3](#comments--spaces) 所有注释开头空一个,方便阅读。 eslint: [`spaced-comment`](http://eslint.org/docs/rules/spaced-comment)
  2. ```javascript
  3. // bad
  4. //is current tab
  5. const active = true;
  6. // good
  7. // is current tab
  8. const active = true;
  9. // bad
  10. /**
  11. *make() returns a new element
  12. *based on the passed-in tag name
  13. */
  14. function make(tag) {
  15. // ...
  16. return element;
  17. }
  18. // good
  19. /**
  20. * make() returns a new element
  21. * based on the passed-in tag name
  22. */
  23. function make(tag) {
  24. // ...
  25. return element;
  26. }
  • 18.4 在你的注释前使用FIXME'或TODO’前缀, 这有助于其他开发人员快速理解你指出的需要重新访问的问题, 或者您建议需要实现的问题的解决方案。 这些不同于常规注释,因为它们是可操作的。 动作是FIXME: - 需要计算出来TODO: - 需要实现
  • 18.5// FIXME:给问题做注释

    1. class Calculator extends Abacus {
    2. constructor() {
    3. super();
    4. // FIXME: shouldn't use a global here
    5. total = 0;
    6. }
    7. }
  • 18.6// TODO:去注释问题的解决方案

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

⬆ back to top

Whitespace

  • 19.1 tab用两个空格. eslint: indent ```javascript // bad function foo() { ∙∙∙∙const name; }

// bad function bar() { ∙const name; }

// good function baz() { ∙∙const name; }

  1. - [19.2](#whitespace--before-blocks) 在大括号前空一格。 eslint: [`space-before-blocks`](http://eslint.org/docs/rules/space-before-blocks.html)
  2. ```javascript
  3. // bad
  4. function test(){
  5. console.log('test');
  6. }
  7. // good
  8. function test() {
  9. console.log('test');
  10. }
  11. // bad
  12. dog.set('attr',{
  13. age: '1 year',
  14. breed: 'Bernese Mountain Dog',
  15. });
  16. // good
  17. dog.set('attr', {
  18. age: '1 year',
  19. breed: 'Bernese Mountain Dog',
  20. });
  • 19.3 在控制语句(if, while 等)的圆括号前空一格。在函数调用和定义时,参数列表和函数名之间不空格。 eslint: keyword-spacing ```javascript // bad if(isJedi) { fight (); }

// good if (isJedi) { fight(); }

// bad function fight () { console.log (‘Swooosh!’); }

// good function fight() { console.log(‘Swooosh!’); }

  1. - [19.4](#whitespace--infix-ops) 用空格来隔开运算符。 eslint: [`space-infix-ops`](http://eslint.org/docs/rules/space-infix-ops.html)
  2. ```javascript
  3. // bad
  4. const x=y+5;
  5. // good
  6. const x = y + 5;
  • 19.5 文件结尾空一行. eslint: eol-last
    1. // bad
    2. import { es6 } from './AirbnbStyleGuide';
    3. // ...
    4. export default es6;
    1. // bad
    2. import { es6 } from './AirbnbStyleGuide';
    3. // ...
    4. export default es6;↵
    1. // good
    2. import { es6 } from './AirbnbStyleGuide';
    3. // ...
    4. export default es6;↵
  • 19.6 当出现长的方法链(>2个)时用缩进。用点开头强调该行是一个方法调用,而不是一个新的语句。eslint: newline-per-chained-call no-whitespace-before-property ```javascript // 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);

  1. - [19.7](#whitespace--after-blocks) 在一个代码块后下一条语句前空一行。
  2. ```javascript
  3. // bad
  4. if (foo) {
  5. return bar;
  6. }
  7. return baz;
  8. // good
  9. if (foo) {
  10. return bar;
  11. }
  12. return baz;
  13. // bad
  14. const obj = {
  15. foo() {
  16. },
  17. bar() {
  18. },
  19. };
  20. return obj;
  21. // good
  22. const obj = {
  23. foo() {
  24. },
  25. bar() {
  26. },
  27. };
  28. return obj;
  29. // bad
  30. const arr = [
  31. function foo() {
  32. },
  33. function bar() {
  34. },
  35. ];
  36. return arr;
  37. // good
  38. const arr = [
  39. function foo() {
  40. },
  41. function bar() {
  42. },
  43. ];
  44. return arr;
  • 19.8 不要用空白行填充块。 eslint: padded-blocks ```javascript // bad function bar() {

    console.log(foo);

}

// also bad if (baz) {

console.log(qux); } else { console.log(foo);

}

// good function bar() { console.log(foo); }

// good if (baz) { console.log(qux); } else { console.log(foo); }

  1. - [19.9](#whitespace--no-multiple-blanks)不要在代码之间使用多个空白行填充。 eslint: [`no-multiple-empty-lines`](https://eslint.org/docs/rules/no-multiple-empty-lines)
  2. ```javascript
  3. // bad
  4. class Person {
  5. constructor(fullName, email, birthday) {
  6. this.fullName = fullName;
  7. this.email = email;
  8. this.setAge(birthday);
  9. }
  10. setAge(birthday) {
  11. const today = new Date();
  12. const age = this.getAge(today, birthday);
  13. this.age = age;
  14. }
  15. getAge(today, birthday) {
  16. // ..
  17. }
  18. }
  19. // good
  20. class Person {
  21. constructor(fullName, email, birthday) {
  22. this.fullName = fullName;
  23. this.email = email;
  24. this.setAge(birthday);
  25. }
  26. setAge(birthday) {
  27. const today = new Date();
  28. const age = getAge(today, birthday);
  29. this.age = age;
  30. }
  31. getAge(today, birthday) {
  32. // ..
  33. }
  34. }
  • 19.10 圆括号里不要加空格。 eslint: space-in-parens ```javascript // bad function bar( foo ) { return foo; }

// good function bar(foo) { return foo; }

// bad if ( foo ) { console.log(foo); }

// good if (foo) { console.log(foo); }

  1. - [19.11](#whitespace--in-brackets) 方括号里不要加空格。看示例。 eslint: [`array-bracket-spacing`](http://eslint.org/docs/rules/array-bracket-spacing.html)
  2. ```javascript
  3. // bad
  4. const foo = [ 1, 2, 3 ];
  5. console.log(foo[ 0 ]);
  6. // good, 逗号分隔符还是要空格的
  7. const foo = [1, 2, 3];
  8. console.log(foo[0]);

// good const foo = { clark: ‘kent’ };

  1. - [19.13](#whitespace--max-len) 避免一行代码超过100个字符(包含空格)。
  2. - 注意: 对于[上面——strings--line-length](#strings--line-length),长字符串不受此规则限制,不应分解。 eslint: [`max-len`](http://eslint.org/docs/rules/max-len.html)
  3. > Why? 这样确保可读性和可维护性
  4. ```javascript
  5. // bad
  6. const foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy;
  7. // bad
  8. $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.'));
  9. // good
  10. const foo = jsonData
  11. && jsonData.foo
  12. && jsonData.foo.bar
  13. && jsonData.foo.bar.baz
  14. && jsonData.foo.bar.baz.quux
  15. && jsonData.foo.bar.baz.quux.xyzzy;
  16. // good
  17. $.ajax({
  18. method: 'POST',
  19. url: 'https://airbnb.com/',
  20. data: { name: 'John' },
  21. })
  22. .done(() => console.log('Congratulations!'))
  23. .fail(() => console.log('You have failed this city.'));
  • 19.14 作为语句的花括号内也要加空格 —— { 后和 } 前都需要空格。 eslint: block-spacing ```javascript // bad function foo() {return true;} if (foo) { bar = 0;}

// good function foo() { return true; } if (foo) { bar = 0; }

  1. - [19.15](#whitespace--comma-spacing) `,` 前不要空格, `,` 后需要空格。 eslint: [`comma-spacing`](https://eslint.org/docs/rules/comma-spacing)
  2. ```javascript
  3. // bad
  4. var foo = 1,bar = 2;
  5. var arr = [1 , 2];
  6. // good
  7. var foo = 1, bar = 2;
  8. var arr = [1, 2];
  • 19.16 计算属性内要空格。参考上述花括号和中括号的规则。 eslint: computed-property-spacing ```javascript // bad obj[foo ] obj[ ‘foo’] var x = {[ b ]: a} obj[foo[ bar ]]

// good obj[foo] obj[‘foo’] var x = { [b]: a } obj[foo[bar]]

  1. - [19.17](#whitespace--func-call-spacing) 调用函数时,函数名和小括号之间不要空格。 eslint: [`func-call-spacing`](https://eslint.org/docs/rules/func-call-spacing)
  2. ```javascript
  3. // bad
  4. func ();
  5. func
  6. ();
  7. // good
  8. func();
  • 19.18 在对象的字面量属性中, key value 之间要有空格。 eslint: key-spacing ```javascript // bad var obj = { “foo” : 42 }; var obj2 = { “foo”:42 };

// good var obj = { “foo”: 42 };

  1. - [19.19](#whitespace--no-trailing-spaces) 行末不要空格。 eslint: [`no-trailing-spaces`](https://eslint.org/docs/rules/no-trailing-spaces)
  2. - [19.20](#whitespace--no-multiple-empty-lines) 避免出现多个空行。 在文件末尾只允许空一行。 eslint: [`no-multiple-empty-lines`](https://eslint.org/docs/rules/no-multiple-empty-lines)
  3. ```javascript
  4. // bad
  5. var x = 1;
  6. var y = 2;
  7. // good
  8. var x = 1;
  9. var y = 2;

⬆ back to top

Commas

  • 20.1 不要前置逗号。 eslint: comma-style ```javascript // 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’, };

  1. - [20.2](#commas--dangling) 额外结尾逗号: **要** eslint: [`comma-dangle`](http://eslint.org/docs/rules/comma-dangle.html)
  2. > Why? 这导致git diffs更清洁。 此外,像Babel这样的转换器会删除转换代码中的额外的逗号,这意味着你不必担心旧版浏览器中的[结尾逗号问题](https://github.com/airbnb/javascript/blob/es5-deprecated/es5/README.md#commas)。
  3. ```diff
  4. // bad - 没有结尾逗号的 git diff
  5. const hero = {
  6. firstName: 'Florence',
  7. - lastName: 'Nightingale'
  8. + lastName: 'Nightingale',
  9. + inventorOf: ['coxcomb chart', 'modern nursing']
  10. };
  11. // good - 有结尾逗号的 git diff
  12. const hero = {
  13. firstName: 'Florence',
  14. lastName: 'Nightingale',
  15. + inventorOf: ['coxcomb chart', 'modern nursing'],
  16. };
  1. // bad
  2. const hero = {
  3. firstName: 'Dana',
  4. lastName: 'Scully'
  5. };
  6. const heroes = [
  7. 'Batman',
  8. 'Superman'
  9. ];
  10. // good
  11. const hero = {
  12. firstName: 'Dana',
  13. lastName: 'Scully',
  14. };
  15. const heroes = [
  16. 'Batman',
  17. 'Superman',
  18. ];
  19. // bad
  20. function createHero(
  21. firstName,
  22. lastName,
  23. inventorOf
  24. ) {
  25. // does nothing
  26. }
  27. // good
  28. function createHero(
  29. firstName,
  30. lastName,
  31. inventorOf,
  32. ) {
  33. // does nothing
  34. }
  35. // good (note that a comma must not appear after a "rest" element)
  36. function createHero(
  37. firstName,
  38. lastName,
  39. inventorOf,
  40. ...heroArgs
  41. ) {
  42. // does nothing
  43. }
  44. // bad
  45. createHero(
  46. firstName,
  47. lastName,
  48. inventorOf
  49. );
  50. // good
  51. createHero(
  52. firstName,
  53. lastName,
  54. inventorOf,
  55. );
  56. // good (note that a comma must not appear after a "rest" element)
  57. createHero(
  58. firstName,
  59. lastName,
  60. inventorOf,
  61. ...heroArgs
  62. )

⬆ back to top

Semicolons

  • 21.1 Yup. eslint: semi

    Why? 当 JavaScript 遇到没有分号结尾的一行,它会执行自动插入分号 Automatic Semicolon Insertion这一规则来决定行末是否加分号。如果JavaScript在你的断行里错误的插入了分号,就会出现一些古怪的行为。当新的功能加到JavaScript里后, 这些规则会变得更复杂难懂。显示的结束语句,并通过配置代码检查去捕获没有带分号的地方可以帮助你防止这种错误。

  1. // bad
  2. (function () {
  3. const name = 'Skywalker'
  4. return name
  5. })()
  6. // good
  7. (function () {
  8. const name = 'Skywalker';
  9. return name;
  10. }());
  11. // good, 行首加分号,避免文件被连接到一起时立即执行函数被当做变量来执行。
  12. ;(() => {
  13. const name = 'Skywalker';
  14. return name;
  15. }());

⬆ back to top

Type Casting & Coercion

  • 22.1 在语句开始执行强制类型转换。

// bad const totalScore = new String(this.reviewScore); // typeof totalScore is “object” not “string”

// bad const totalScore = this.reviewScore + ‘’; // invokes this.reviewScore.valueOf()

// bad const totalScore = this.reviewScore.toString(); // 不保证返回string

// good const totalScore = String(this.reviewScore);

  1. - [22.3](#coercion--numbers) Numbers: `Number` 做类型转换,`parseInt`转换string常需要带上基数。 eslint: [`radix`](http://eslint.org/docs/rules/radix)
  2. ```javascript
  3. const inputValue = '4';
  4. // bad
  5. const val = new Number(inputValue);
  6. // bad
  7. const val = +inputValue;
  8. // bad
  9. const val = inputValue >> 0;
  10. // bad
  11. const val = parseInt(inputValue);
  12. // good
  13. const val = Number(inputValue);
  14. // good
  15. const val = parseInt(inputValue, 10);
  • 22.4 请在注释中解释为什么要用移位运算和你在做什么。无论你做什么狂野的事,比如由于 parseInt 是你的性能瓶颈导致你一定要用移位运算。 请说明这个是因为性能原因,
    1. // good
    2. /**
    3. * parseInt是代码运行慢的原因
    4. * 用Bitshifting将字符串转成数字使代码运行效率大幅增长
    5. */
    6. const val = inputValue >> 0;
  • 22.5 注意: 用移位运算要小心. 数字使用64-位表示的,但移位运算常常返回的是32为整形source)。移位运算对大于32位的整数会导致意外行为。Discussion. 最大的32位整数是 2,147,483,647:
    1. 2147483647 >> 0 //=> 2147483647
    2. 2147483648 >> 0 //=> -2147483648
    3. 2147483649 >> 0 //=> -2147483647
  • 22.6 布尔: ```javascript const age = 0;

// bad const hasAge = new Boolean(age);

// good const hasAge = Boolean(age);

// best const hasAge = !!age;

  1. **[⬆ back to top](#%E7%9B%AE%E5%BD%95)**
  2. <a name="85a449e7"></a>
  3. ## Naming Conventions
  4. - [23.1](#naming--descriptive) 避免用一个字母命名,让你的命名可描述。 eslint: [`id-length`](http://eslint.org/docs/rules/id-length)
  5. ```javascript
  6. // bad
  7. function q() {
  8. // ...
  9. }
  10. // good
  11. function query() {
  12. // ...
  13. }
  • 23.2 用小驼峰式命名你的对象、函数、实例。 eslint: camelcase ```javascript // bad const OBJEcttsssss = {}; const this_is_my_object = {}; function c() {}

// good const thisIsMyObject = {}; function thisIsMyFunction() {}

  1. - [23.3](#naming--PascalCase) 用大驼峰式命名类。 eslint: [`new-cap`](http://eslint.org/docs/rules/new-cap.html)
  2. ```javascript
  3. // bad
  4. function user(options) {
  5. this.name = options.name;
  6. }
  7. const bad = new user({
  8. name: 'nope',
  9. });
  10. // good
  11. class User {
  12. constructor(options) {
  13. this.name = options.name;
  14. }
  15. }
  16. const good = new User({
  17. name: 'yup',
  18. });
  • 23.4 不要用前置或后置下划线。 eslint: no-underscore-dangle

    Why? JavaScript 没有私有属性或私有方法的概念。尽管前置下划线通常的概念上意味着“private”,事实上,这些属性是完全公有的,因此这部分也是你的API的内容。这一概念可能会导致开发者误以为更改这个不会导致崩溃或者不需要测试。 如果你想要什么东西变成“private”,那就不要让它在这里出现。

  1. // bad
  2. this.__firstName__ = 'Panda';
  3. this.firstName_ = 'Panda';
  4. this._firstName = 'Panda';
  5. // good
  6. this.firstName = 'Panda';
  • 23.5 不要保存引用this, 用箭头函数或函数绑定——Function#bind. ```javascript // bad function foo() { const self = this; return function () { console.log(self); }; }

// bad function foo() { const that = this; return function () { console.log(that); }; }

// good function foo() { return () => { console.log(this); }; }

  1. - [23.6](#naming--filename-matches-export) export default导出模块A,则这个文件名也叫A.*, import 时候的参数也叫A 大小写完全一致。
  2. ```javascript
  3. // file 1 contents
  4. class CheckBox {
  5. // ...
  6. }
  7. export default CheckBox;
  8. // file 2 contents
  9. export default function fortyTwo() { return 42; }
  10. // file 3 contents
  11. export default function insideDirectory() {}
  12. // in some other file
  13. // bad
  14. import CheckBox from './checkBox'; // PascalCase import/export, camelCase filename
  15. import FortyTwo from './FortyTwo'; // PascalCase import/filename, camelCase export
  16. import InsideDirectory from './InsideDirectory'; // PascalCase import/filename, camelCase export
  17. // bad
  18. import CheckBox from './check_box'; // PascalCase import/export, snake_case filename
  19. import forty_two from './forty_two'; // snake_case import/filename, camelCase export
  20. import inside_directory from './inside_directory'; // snake_case import, camelCase export
  21. import index from './inside_directory/index'; // requiring the index file explicitly
  22. import insideDirectory from './insideDirectory/index'; // requiring the index file explicitly
  23. // good
  24. import CheckBox from './CheckBox'; // PascalCase export/import/filename
  25. import fortyTwo from './fortyTwo'; // camelCase export/import/filename
  26. import insideDirectory from './insideDirectory'; // camelCase export/import/directory name/implicit "index"
  27. // ^ supports both insideDirectory.js and insideDirectory/index.js
  • 23.7 当你export-default一个函数时,函数名用小驼峰,文件名需要和函数名一致。 ```javascript function makeStyleGuide() { // … }

export default makeStyleGuide;

  1. - [23.8](#naming--PascalCase-singleton) 当你export一个结构体/类/单例/函数库/对象 时用大驼峰。
  2. ```javascript
  3. const AirbnbStyleGuide = {
  4. es6: {
  5. }
  6. };
  7. export default AirbnbStyleGuide;
  • 23.9 简称和缩写应该全部大写或全部小写。

    Why? 名字都是给人读的,不是为了适应电脑的算法的。

  1. // bad
  2. import SmsContainer from './containers/SmsContainer';
  3. // bad
  4. const HttpRequests = [
  5. // ...
  6. ];
  7. // good
  8. import SMSContainer from './containers/SMSContainer';
  9. // good
  10. const HTTPRequests = [
  11. // ...
  12. ];
  13. // best
  14. import TextMessageContainer from './containers/TextMessageContainer';
  15. // best
  16. const Requests = [
  17. // ...
  18. ];
  • 23.10 你可以用全大写字母设置静态变量,他需要满足三个条件。

    1. 导出变量
    2. const 定义的, 保证不能被改变
    3. 这个变量是可信的,他的子属性都是不能被改变的

      Why? 这是一个附加工具,帮助开发者去辨识一个变量是不是不可变的。

    • 对于所有的 const 变量呢? —— 这个是不必要的。大写变量不应该在同一个文件里定义并使用, 它只能用来作为导出变量。 赞同!
    • 那导出的对象呢? —— 大写变量处在export的最高级(e.g. EXPORTED_OBJECT.key) 并且他包含的所有子属性都是不可变的。 ```javascript // bad const PRIVATE_VARIABLE = ‘should not be unnecessarily uppercased within a file’;

// bad export const THING_TO_BE_CHANGED = ‘should obviously not be uppercased’;

// bad export let REASSIGNABLE_VARIABLE = ‘do not use let with uppercase variables’;

// —-

// allowed but does not supply semantic value export const apiKey = ‘SOMEKEY’;

// better in most cases export const API_KEY = ‘SOMEKEY’;

// —-

// bad - unnecessarily uppercases key while adding no semantic value export const MAPPING = { KEY: ‘value’ };

// good export const MAPPING = { key: ‘value’ };

  1. **[⬆ back to top](#%E7%9B%AE%E5%BD%95)**
  2. <a name="Accessors"></a>
  3. ## Accessors
  4. - [24.1](#accessors--not-required) 不需要使用属性的访问器函数。
  5. - [24.2](#accessors--no-getters-setters) 不要使用JavaScriptgetters/setters,因为他们会产生副作用,并且难以测试、维护和理解。相反的,你可以用 getVal()和setVal('hello')去创造你自己的accessor函数
  6. ```javascript
  7. // bad
  8. class Dragon {
  9. get age() {
  10. // ...
  11. }
  12. set age(value) {
  13. // ...
  14. }
  15. }
  16. // good
  17. class Dragon {
  18. getAge() {
  19. // ...
  20. }
  21. setAge(value) {
  22. // ...
  23. }
  24. }
  • 24.3 如果属性/方法是boolean, 用 isVal()hasVal() ```javascript // bad if (!dragon.age()) { return false; }

// good if (!dragon.hasAge()) { return false; }

  1. - [24.4](#accessors--consistent) get()和set()函数是可以的,但是要一起用
  2. ```javascript
  3. class Jedi {
  4. constructor(options = {}) {
  5. const lightsaber = options.lightsaber || 'blue';
  6. this.set('lightsaber', lightsaber);
  7. }
  8. set(key, val) {
  9. this[key] = val;
  10. }
  11. get(key) {
  12. return this[key];
  13. }
  14. }

⬆ back to top

Events

  • 25.1 通过哈希而不是原始值向事件装载数据时(不论是DOM事件还是像Backbone事件的很多属性)。 这使得后续的贡献者(程序员)向这个事件装载更多的数据时不用去找或者更新每个处理器。例如: ```javascript // bad $(this).trigger(‘listingUpdated’, listing.id);

$(this).on(‘listingUpdated’, (e, listingId) => { // do something with listingId });

  1. - <br />prefer:
  2. ```javascript
  3. // good
  4. $(this).trigger('listingUpdated', { listingId: listing.id });
  5. ...
  6. $(this).on('listingUpdated', (e, data) => {
  7. // do something with data.listingId
  8. });

⬆ back to top

jQuery

  • 26.1 jQuery对象用$变量表示。 ```javascript // bad const sidebar = $(‘.sidebar’);

// good const $sidebar = $(‘.sidebar’);

// good const $sidebarBtn = $(‘.sidebar-btn’);

  1. - [26.2](#jquery--cache) 暂存jQuery查找
  2. ```javascript
  3. // bad
  4. function setSidebar() {
  5. $('.sidebar').hide();
  6. // ...
  7. $('.sidebar').css({
  8. 'background-color': 'pink'
  9. });
  10. }
  11. // good
  12. function setSidebar() {
  13. const $sidebar = $('.sidebar');
  14. $sidebar.hide();
  15. // ...
  16. $sidebar.css({
  17. 'background-color': 'pink'
  18. });
  19. }
  • 26.3 DOM查找用层叠式$('.sidebar ul') 或 父节点 > 子节点 $('.sidebar > ul'). jsPerf
  • 26.4 用jQuery对象查询作用域的find方法查询 ```javascript // bad $(‘ul’, ‘.sidebar’).hide();

// bad $(‘.sidebar’).find(‘ul’).hide();

// good $(‘.sidebar ul’).hide();

// good $(‘.sidebar > ul’).hide();

// good $sidebar.find(‘ul’).hide();

  1. **[⬆ back to top](#%E7%9B%AE%E5%BD%95)**
  2. <a name="903ae181"></a>
  3. ## ES5 兼容性
  4. - [27.1](#es5-compat--kangax) 参考[Kangax](https://twitter.com/kangax/)的ES5[兼容性列表](https://kangax.github.io/es5-compat-table/).
  5. **[⬆ back to top](#%E7%9B%AE%E5%BD%95)**
  6. <a name="c64dfd7d"></a>
  7. ## ECMAScript 6+ (ES 2015+) Styles
  8. - [28.1](#es6-styles) 这是收集到的各种ES6特性的链接
  9. 1. [箭头函数——Arrow Functions](#arrow-functions)
  10. 1. [类——Classes](#classes--constructors)
  11. 1. [对象缩写——Object Shorthand](#es6-object-shorthand)
  12. 1. [对象简写——Object Concise](#es6-object-concise)
  13. 1. [对象计算属性——Object Computed Properties](#es6-computed-properties)
  14. 1. [模板字符串——Template Strings](#es6-template-literals)
  15. 1. [解构赋值——Destructuring](#destructuring)
  16. 1. [默认参数——Default Parameters](#es6-default-parameters)
  17. 1. [Rest](#es6-rest)
  18. 1. [Array Spreads](#es6-array-spreads)
  19. 1. [Let and Const](#references)
  20. 1. [幂操作符——Exponentiation Operator](#es2016-properties--exponentiation-operator)
  21. 1. [迭代器和生成器——Iterators and Generators](#iterators-and-generators)
  22. 1. [模块——Modules](#modules)
  23. - [28.2](#tc39-proposals) 不要用[TC39 proposals](https://github.com/tc39/proposals), TC39还没有到 stage 3。
  24. > Why? [它还不是最终版](https://tc39.github.io/process-document/), 他可能还有很多变化,或者被撤销。 我们想要用的是 JavaScript, 提议还不是JavaScript。
  25. **[⬆ back to top](#%E7%9B%AE%E5%BD%95)**
  26. <a name="e706fe50"></a>
  27. ## Standard Library
  28. [标准库](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects)中包含一些功能受损但是由于历史原因遗留的工具类
  29. - [29.1](#standard-library--isnan) `Number.isNaN` 代替全局的 `isNaN`.<br />
  30. eslint: [`no-restricted-globals`](https://eslint.org/docs/rules/no-restricted-globals)
  31. > Why? 全局 `isNaN` 强制把非数字转成数字, 然后对于任何强转后为 `NaN` 的变量都返回 `true`
  32. > 如果你想用这个功能,就显式的用它。
  33. ```javascript
  34. // bad
  35. isNaN('1.2'); // false
  36. isNaN('1.2.3'); // true
  37. // good
  38. Number.isNaN('1.2.3'); // false
  39. Number.isNaN(Number('1.2.3')); // true
  • 29.2Number.isFinite 代替 isFinite.
    eslint: no-restricted-globals

    Why? 理由同上,会把一个非数字变量强转成数字,然后做判断。

  1. // bad
  2. isFinite('2e3'); // true
  3. // good
  4. Number.isFinite('2e3'); // false
  5. Number.isFinite(parseInt('2e3', 10)); // true

Testing

  • 30.1 Yup.
    1. function foo() {
    2. return true;
    3. }
  • 30.2 No, but seriously:
  • 无论用那个测试框架,你都需要写测试。
  • 尽量去写很多小而美的纯函数,减少突变的发生
  • 小心 stub 和 mock —— 这会让你的测试变得脆弱。
  • 在 Airbnb 首选 mochatape 偶尔被用来测试一些小的,独立的模块。
  • 100%测试覆盖率是我们努力的目标,即便实际上很少达到。
  • 每当你修了一个bug, 都要写一个回归测试。 一个bug修复了,没有回归测试,很可能以后会再次出问题。

⬆ back to top

Performance

⬆ back to top

Resources

Learning ES6

Read This

Tools

Other Style Guides

Other Styles

Further Reading

Books

Blogs

Podcasts

⬆ back to top

In the Wild

This is a list of organizations that are using this style guide. Send us a pull request and we’ll add you to the list.

⬆ back to top

Translation

This style guide is also available in other languages:

The JavaScript Style Guide Guide

Chat With Us About JavaScript

Contributors

License

(The MIT License)

Copyright (c) 2012 Airbnb

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
‘Software’), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

⬆ back to top

Amendments

We encourage you to fork this guide and change the rules to fit your team’s style guide. Below, you may list some amendments to the style guide. This allows you to periodically update your style guide without having to deal with merge conflicts.

};