谷歌JavaScript风格指南的13个值得注意的地方

原文链接:https://medium.freecodecamp.org/google-publishes-a-javascript-style-guide-here-are-some-key-lessons-1810b8ad050b

1、空格代替tab

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// bad
function foo() {
∙∙∙∙let name;
}

// bad
function bar() {
let name;
}

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

2、不能省略分号

1
2
3
4
5
6
7
8
9
10
// bad
let luke = {}
let leia = {}
[luke, leia].forEach(jedi => jedi.father = 'vader')
// good
let luke = {};
let leia = {};
[luke, leia].forEach((jedi) => {
jedi.father = 'vader';
});

3、暂时不要使用ES6 module

1
2
3
4
5
6
7
8
9
10
11
// Don't do this kind of thing yet:
//------ lib.js ------
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}

//------ main.js ------
import { square, diag } from 'lib';

4、不推荐代码水平对齐

1
2
3
4
5
6
7
8
9
10
// bad
{
tiny: 42,
longer: 435,
};
// good
{
tiny: 42,
longer: 435,
};

5、杜绝var

1
2
3
4
// bad
var example = 42;
// good
const example = 42;

6、优先使用箭头函数

1
2
3
4
5
6
7
8
9
10
11
// 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;
});

7、使用模板字符串取代连接字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 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}?`;
}

8、不要使用续行符分割长字符串

1
2
3
4
5
6
7
8
9
10
// bad (sorry, this doesn't show up well on mobile)
const longString = 'This is a very long string that \
far exceeds the 80 column limit. It unfortunately \
contains long stretches of spaces due to how the \
continued lines are indented.';
// good
const longString = 'This is a very long string that ' +
'far exceeds the 80 column limit. It does not contain ' +
'long stretches of spaces since the concatenated ' +
'strings are cleaner.';

9、优先使用for…of

对于ES6语言,现在有3种不同的循环。所有的都可以使用,尽管在可能的时候应该首选循环,但Google仍推荐使用for...of

10、不要使用eval语句

1
2
3
4
5
6
7
8
// bad
let obj = { a: 20, b: 30 };
let propName = getPropName(); // returns "a" or "b"
eval( 'var result = obj.' + propName );
// good
let obj = { a: 20, b: 30 };
let propName = getPropName(); // returns "a" or "b"
let result = obj[ propName ]; // obj[ "a" ] is the same as obj.a

11、常量的命名规范

常量命名应该使用全大写格式,并用下划线分割

1
2
3
4
// bad
const number = 5;
// good
const NUMBER = 5;

12、每次只声明一个变量

每一个变量声明都应该只对应着一个变量。不应该出现像let a = 1,b = 2;这样的语句

1
2
3
4
5
6
// bad
let a = 1, b = 2, c = 3;
// good
let a = 1;
let b = 2;
let c = 3;

13、使用单引号

只允许使用单引号包裹普通字符串,禁止使用双引号。如果字符串中包含单引号字符,应该使用模板字符串。

1
2
3
4
5
6
7
8
// bad
let directive = "No identification of self or mission."
// bad
let saying = 'Say it ain\u0027t so.';
// good
let directive = 'No identification of self or mission.';
// good
let saying = `Say it ain't so`;

参考资料:

参考文章: https://segmentfault.com/a/1190000014121644