一些达成共识的JavaScript编码风格约定
http://www.csdn.net/article/2013-07-11/2816196-javascript-code-style-guide
JavaScript Style Guide
1. Linting
Use JSHint to detect errors and potential problems. Every jQuery project has a Grunt task for linting all JavaScript files:grunt
jshint. The options for JSHint are stored in a .jshintrc file; many
repositories will have multiple .jshintrc files based on the type of code in
each directory.
Each .jshintrc file follows a specific format. All options must be alphabetized
and grouped:
|
1
2
3
4
5
6
7
8
9
10
11
12
|
|
The following common options must be used in all projects:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
|
2. Spacing
- Indentation with tabs.
- No end of line whitespace.
- No blank line whitespace.
- Liberal spacing in code.
-
if/else/for/while/tryalways have braces and always go on multiple lines.
Bad Examples
|
1
2
3
4
5
6
7
8
9
10
11
|
|
Good Examples
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
|
Arrays and Objects
Empty objects and arrays don't need filler spaces
|
1
2
|
|
Function Calls
Always include extra spaces around the arguments:
|
1
2
3
4
5
6
7
|
|
Exceptions:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
|
3. Assignments
Assignments should always have a semicolon after them.
Semicolons should always be followed by a newline.
Assignments in a declaration should always be on their own line. Declarations that don't have an assignment should be listed together at the start of the declaration. For example:
|
1
2
3
4
5
6
7
8
9
10
11
|
|
4. Equality
Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by
way of null.
|
1
2
|
|
5. Type Checks
-
String:
typeof object === "string" -
Number:
typeof object === "number" -
Boolean:
typeof object === "boolean" -
Object:
typeof object === "object" -
Plain Object:
jQuery.isPlainObject( object ) -
Function:
jQuery.isFunction( object ) -
Array:
jQuery.isArray( object ) -
Element:
object.nodeType -
null:
object === null -
null or undefined:
object == null -
undefined:
-
Global Variables:
typeof variable === "undefined" -
Local Variables:
variable === undefined -
Properties:
object.prop === undefined
-
Global Variables:
6. Comments
Single line comments go OVER the line they refer to:
|
1
2
|
|
For long comments, use:
|
1
2
3
|
|
Inline comments are allowed as an exception when used to annotate special arguments in formal parameter lists:
|
1
2
3
|
|
7. Quotes
jQuery uses double quotes.
|
1
|
|
Strings that require inner quoting must use double outside and single inside.
|
1
|
|
8. DOM Node Rules
.nodeName should always be used in favor of .tagName.
.nodeType should be used to determine the classification of a node (not .nodeName).
本文提供了一套详细的JavaScript编码规范,包括使用JSHint进行错误检测、代码缩进、空格使用、赋值语句格式、严格等号使用、类型检查、注释规范、引用符号选择及DOM节点操作的最佳实践。
2343

被折叠的 条评论
为什么被折叠?



