javascript格式建议(JavaScript Style Guide)

来源:互联网 发布:淘宝助理新建宝贝 编辑:程序博客网 时间:2024/05/29 19:21

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.

使用JSHint可以检查出错误和潜在的问题。每一个jquery项目拥有一个grunt 列表,用于linting所有的javascript文件:grunt jshint.

JSHint的配置包含在以.jshintrc结尾的文件里面;许多代码仓库都有多个以.jshintrc结尾的文件。这些文件基于各自目录下面的代码

Each .jshintrc file follows a specific format. All options must be alphabetized and grouped:

每一个以.jshintrc接吻的文件都遵循一种特定的格式。所有的选项必须按字母排序并且分组:

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

If the project supports browsers which do not implement ES5, then the es3 option must be included with the repo-specific options.

如果一个项目所支持的浏览器并没有实现ES5,那么他的repo-specific文件的配置项中必须包含es3这个配置项。

linkSpacing

In general, the jQuery style guide encourages liberal spacing for improved human readability. The minification process creates a file that is optimized for browsers to read and process.

总的来说,jquery的风格鼓励自由的空格间距以提高人们的可读性。最小的缩进处理可以让浏览器更加方便的读取和处理文件。

  • Indentation with tabs.
  • 使用tabs键缩进
  • No whitespace at the end of line or on blank lines.
  • 在一行的结束或者空行不要包含空格。
  • Lines should be no longer than 80 characters, and must not exceed 100 (counting tabs as 4 spaces). There are 2 exceptions, both allowing the line to exceed 100 characters:
  • 每一行最好不要超过80个字母,而且最好长度不要超过100(一个tabs计算为4个空格)。但是在两种情况下,允许一行超过100个字母。
    • If the line contains a comment with a long URL.
    • 如果这一行包含了一个URL文本
    • If the line contains a regex literal. This prevents having to use the regex constructor which requires otherwise unnecessary string escaping.
    • 如果这一行包含了一个正则表达式。这样可以防止使用正则表达式的函数使用其他不必要的字符进行转义。
  • if/else/for/while/try always have braces and always go on multiple lines.
  • if/else/for/while/try 总是有括号,总是包含多行。
  • Unary special-character operators (e.g., !++) must not have space next to their operand.
  • 一元操作符(例如:!,++)在他们的下一个操作数之间不能包含空格。
  • Any , and ; must not have preceding space.
  • 任何,和;的前面都不能包含空格。
  • Any ; used as a statement terminator must be at the end of the line.
  • 任何以;作为结尾的语句都要换行。
  • Any : after a property name in an object definition must not have preceding space.
  • 一个对象的属性名都必须紧跟:之间不能有空格。
  • The ? and : in a ternary conditional must have space on both sides.
  • 三元操作符的?和:之间必须有空格。
  • No filler spaces in empty constructs (e.g., {}[]fn())
  • 在无参构造函数的括号里面不能有空格(例如:{}[]fn())
  • New line at the end of each file.
  • 每一行结束后都要新起一行
  • If the entire file is wrapped in a closure, the function body is not indented. See full file closures for examples.
  • 如果整个文件包在一个闭包,函数体不缩进。看到完整的文件关闭的例子。

linkBad Examples

1
2
3
4
// Bad
if(condition) doSomething();
while(!condition) iterating++;
for(var i=0;i<100;i++) object[array[i]] = someFn(i);

linkGood 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
var i = 0;
if ( condition ) {
doSomething();
} else if ( otherCondition ) {
somethingElse();
} else {
otherThing();
}
while ( !condition ) {
iterating++;
}
for ( ; i < 100; i++ ) {
object[ array[ i ] ] = someFn( i );
}
try {
// Expressions
} catch ( e ) {
// Expressions
}
array = [ "*" ];
array = [ a, b ];
foo( arg );
foo( options, object[ property ] );
foo( [ a, b ], "property", { c: d } );
foo( { a: "alpha", b: "beta" } );
foo( [ a, b ] );
foo( {
a: "alpha",
b: "beta"
} );
foo( function() {
// Do stuff
}, options );
foo( data, function() {
// Do stuff
} );

linkObject and Array Expressions

Object and array expressions can be on one line if they are short (remember the line length limits). When an expression is too long to fit on one line, there must be one property or element per line, with the opening and closing braces each on their own lines. Property names only need to be quoted if they are reserved words or contain special characters:

对象和数组表达式如果很短的话可以作为一行(记住一行的长度限制),如果一个表达式对于一行来说实在太长,每行必须有一个属性或元素,在打开和关闭括号自己每一行。属性名称只需要引用保留字或包含特殊字符:

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
59
// Bad
map = { ready: 9,
when: 4, "you are": 15 };
array = [ 9,
4,
15 ];
array = [ {
key: val
} ];
array = [ {
key: val
}, {
key2: val2
} ];
// Good
map = { ready: 9, when: 4, "you are": 15 };
array = [ 9, 4, 15 ];
array = [ { key: val } ];
array = [ { key: val }, { key2: val2 } ];
array = [
{ key: val },
{ key2: val2 }
];
// Good as well
map = {
ready: 9,
when: 4,
"you are": 15
};
array = [
9,
4,
15
];
array = [
{
key: val
}
];
array = [
{
key: val
},
{
key2: val2
}
];

linkMulti-line Statements

When a statement is too long to fit on one line, line breaks must occur after an operator.

当一个语句太长而无法适应在一行上,换行符必须在运算符后。

1
2
3
4
5
6
7
// Bad
var html = "<p>The sum of " + a + " and " + b + " plus " + c
+ " is " + ( a + b + c );
// Good
var html = "<p>The sum of " + a + " and " + b + " plus " + c +
" is " + ( a + b + c );

Lines should be broken into logical groups if it improves readability, such as splitting each expression of a ternary operator onto its own line even if both will fit on a single line.,

换行必须以逻辑进行分组,如果它能提高可读性。如分裂每个三元操作符的表达式到自己的线,即使都适合在一行。

1
2
3
var baz = firstCondition( foo ) && secondCondition( bar ) ?
qux( foo, bar ) :
foo;

When a conditional is too long to fit on one line, successive lines must be indented one extra level to distinguish them from the body.

当一个条件适合一行太长,连续线必须缩进一个额外的层面,以区别于主体。

1
2
3
4
if ( firstCondition() && secondCondition() &&
thirdCondition() ) {
doStuff();
}

linkChained Method Calls

When a chain of method calls is too long to fit on one line, there must be one call per line, with the first call on a separate line from the object the methods are called on. If the method changes the context, an extra level of indentation must be used.

当一个方法调用链太长,适合在一行,每行必须有一个方法调用,第一个对象调用的方法在一个单独的行上。如果方法改变了文本,必须使用一个额外的缩进级别。

1
2
3
4
5
6
elements
.addClass( "foo" )
.children()
.html( "hello" )
.end()
.appendTo( "body" );

linkFull File Closures

When an entire file is wrapped in a closure, the body of the closure is not indented.

当整个文件包在一个闭包,闭包的主体不能缩进。

1
2
3
4
5
( function( $ ) {
// This doesn't get indented
} )( jQuery );
1
2
3
4
5
module.exports = function( grunt ) {
// This doesn't get indented
};

The same applies to AMD wrappers.

这同样适用于AMD包装器。

1
2
3
4
5
6
7
8
9
define( [
"foo",
"bar",
"baz"
], function( foo, bar, baz ) {
// This doesn't get indented
} );

For UMD, the factory is indented to visually differentiate it from the body.

UMD格式,工厂是在视觉上区分它的身体缩进。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [
"jquery"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}( function( $ ) {
// This doesn't get indented
} ) );

linkConstructors

Constructor functions should always be invoked with argument lists, even when such lists are empty.

应该调用构造函数参数列表,即使这样的列表是空的。

1
2
throw new Error();
when = time || new Date();

When property access or method invocation is immediately performed on the result of a constructor function, clarify precedence with wrapping parentheses.

当属性访问或方法调用是立即执行构造函数的结果,通过包装括号明确优先级。

1
2
detachedMode = ( new TemplateFactory( settings ) ).nodeType === 11;
match = ( new RegExp( pattern ) ).exec( input );

linkEquality

Strict equality checks (===) must be used in favor of abstract equality checks (==). 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;

linkType 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
    • 属性

linkComments

Comments are always preceded by a blank line. Comments start with a capital first letter, but don't require a period at the end, unless you're writing full sentences. There must be a single space between the comment token and the comment text.

之前的评论总是一个空行。评论用大写第一个字母开始,但最后不需要句号,除非你写完整的句子。必须有一个空格和注释标记之间的文本发表评论。

Single line comments go over the line they refer to:

1
2
3
4
5
6
// We need an explicit "bar", because later in the code foo is checked.
var foo = "bar";
// Even long comments that span
// multiple lines use the single
// line comment form.

Multi-line comments are only used for file and function headers.

多行注释仅用于文件和函数头。

Inline comments are allowed as an exception when used to annotate special arguments in formal parameter lists or when needed to support a specific development tool:

允许内联注释作为例外,当用来标注特殊参数形式参数列表或当需要支持一个特定的开发工具:

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

Do not write API documentation in comments. API documentation lives in its own repository.

不在注释里面写API文档。API文档在专门的地方。

linkQuotes

jQuery uses double quotes.

jQuery使用双引号。

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>";

linkSemicolons

Use them. Never rely on ASI.

分号

使用它们。不要依赖ASI

linkNaming Conventions

Variable and function names should be full words, using camel case with a lowercase first letter. Names should be descriptive but not excessively so. Exceptions are allowed for iterators, such as the use of i to represent the index in a loop. Constructors do not need a capital first letter.

命名约定

变量和函数名应该完整的单词,使用驼峰式大小写小写首字母。名字应该是描述性的但不是非常困难。例外是允许迭代器,如使用我代表指数在一个循环中。构造函数不需要大写首字母。

linkGlobal Variables

Each project may expose at most one global variable.

全局变量

每个项目最多可能暴露一个全局变量。

linkDOM Node Rules

.nodeName must always be used in favor of .tagName.

DOM节点的规则

.nodeName必须使用支持.tagName。


.nodeType must be used to determine the classification of a node (not .nodeName).

.nodeType必须用于确定节点的分类(不是.nodeName)。

linkSwitch Statements

The usage of switch statements is generally discouraged, but can be useful when there are a large number of cases - especially when multiple cases can be handled by the same block, or fall-through logic (the default case) can be leveraged.

switch语句的使用通常是沮丧,但可以有用,当有大量的情况,尤其是当多个情况下可以由相同的块,或失败逻辑可以利用(默认情况下)。

When using switch statements:

  • Use a break for each case other than default.
  • Align case statements with the switch.
1
2
3
4
5
6
7
8
9
10
11
switch ( event.keyCode ) {
case $.ui.keyCode.ENTER:
case $.ui.keyCode.SPACE:
x();
break;
case $.ui.keyCode.ESCAPE:
y();
break;
default:
z();
}
0 0
原创粉丝点击