JavaScript编码风格

本文提供了一套详细的JavaScript编码规范,包括使用JSHint进行错误检测、代码缩进、空格使用、赋值语句格式、严格等号使用、类型检查、注释规范、引用符号选择及DOM节点操作的最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一些达成共识的JavaScript编码风格约定

http://www.youkuaiyun.com/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
{
"common1": true,
"common2": true,
"repoSpecific1": true,
"repoSpecific2": true,
"globals": {
"repoGlobal1": true,
"repoGlobal2": false
}
}

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
{
"boss": true,
"curly": true,
"eqeqeq": true,
"eqnull": true,
"expr": true,
"immed": true,
"noarg": true,
"onevar": true,
"quotmark": "double",
"smarttabs": true,
"trailing": true,
"undef": true,
"unused": true
}

2. Spacing

  • Indentation with tabs.
  • No end of line whitespace.
  • No blank line whitespace.
  • Liberal spacing in code.
  • if/else/for/while/try always have braces and always go on multiple lines.

Bad Examples

1
2
3
4
5
6
7
8
9
10
11
// Bad
if(condition) doSomething();
// Bad
while(condition) iterating++;
// Bad
for(var i=0;i<100;i++) someIterativeFn();
// Bad
object[array[0]];

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
// Good
if ( condition ) {
// expressions
}
// Good
while ( condition ) {
// expressions
}
// Good
var i = 0;
for ( ; i < 100; i++ ) {
// expressions
}
// Good
var prop;
for ( prop in object ) {
// expressions
}
// Good
if ( condition ) {
// expressions
} else {
// expressions
}
// Good
if ( condition ) {
// expressions
} else if ( condition ) {
// expressions
} else {
// expressions
}
// Good
try {
// expressions
} catch ( e ) {
// expressions
}
// Good
try {
// expressions
} catch ( e ) {
// expressions
} finally {
// expressions
}
// Good
object[ array[ 0 ] ];

Arrays and Objects

Empty objects and arrays don't need filler spaces

1
2
var object = {},
array = [];

Function Calls

Always include extra spaces around the arguments:

1
2
3
4
5
6
7
foo( arg );
foo( "string", object );
foo( options, callback );
foo( node, "property", 2 );

Exceptions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Empty function calls
foo();
// Functions with callbacks
foo(function() {
// Note there is no extra space between the first paren
// of the executing function call and the word "function"
});
// Function accepting an array, no space
foo([ "alpha", "beta" ]);
// Function accepting an object, no space
foo({
a: "alpha",
b: "beta"
});

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
// Bad
var foo = true;
var bar = false;
var a;
var b;
var c;
// Good
var a, b, c,
foo = true,
bar = false;

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
// Check for both undefined and null values, for some important reason.
undefOrNull == null;

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

6. Comments

Single line comments go OVER the line they refer to:

1
2
// We need an explicit "bar", because later in the code foo is checked.
var foo = "bar";

For long comments, use:

1
2
3
/*
Four score and seven—pause—minutes ago...
*/

Inline comments are allowed as an exception when used to annotate special arguments in formal parameter lists:

1
2
3
function foo( types, selector, data, fn, /*INTERNAL*/ one ) {
// do stuff.
}

7. Quotes

jQuery uses double quotes.

1
var double = "I am wrapped in double quotes";

Strings that require inner quoting must use double outside and single inside.

1
var html = "<div id='my-id'></div>";

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).



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值