您的位置:首页 > Web前端 > JavaScript

javascript格式建议(JavaScript Style Guide)

2015-10-18 23:43 615 查看


Linting

UseJSHinttodetecterrorsandpotentialproblems.EveryjQueryprojecthasaGrunttaskforlintingallJavaScriptfiles:
grunt
jshint
.TheoptionsforJSHintarestoredina
.jshintrc
file;manyrepositories
willhavemultiple
.jshintrc
filesbasedonthetypeofcodeineachdirectory.

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

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

Each
.jshintrc
filefollowsaspecificformat.Alloptionsmustbealphabetizedand
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
}
}

Thefollowingcommonoptionsmustbeusedinallprojects:

所有的项目都必须包含以下所列出的配置选项:

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
}

IftheprojectsupportsbrowserswhichdonotimplementES5,thenthe
es3
option
mustbeincludedwiththerepo-specificoptions.

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


linkSpacing

Ingeneral,thejQuerystyleguideencouragesliberalspacingforimprovedhumanreadability.Theminificationprocesscreatesafilethatisoptimizedforbrowserstoreadandprocess.

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

Indentationwithtabs.

使用tabs键缩进

Nowhitespaceattheendoflineoronblanklines.

在一行的结束或者空行不要包含空格。

Linesshouldbenolongerthan80characters,andmustnotexceed100(countingtabsas4spaces).Thereare2exceptions,bothallowingthelinetoexceed100characters:

每一行最好不要超过80个字母,而且最好长度不要超过100(一个tabs计算为4个空格)。但是在两种情况下,允许一行超过100个字母。

IfthelinecontainsacommentwithalongURL.

如果这一行包含了一个URL文本

Ifthelinecontainsaregexliteral.Thispreventshavingtousetheregexconstructorwhichrequiresotherwiseunnecessarystringescaping.

如果这一行包含了一个正则表达式。这样可以防止使用正则表达式的函数使用其他不必要的字符进行转义。

if
/
else
/
for
/
while
/
try
always
havebracesandalwaysgoonmultiplelines.

if
/
else
/
for
/
while
/
try
总是有括号,总是包含多行。

Unaryspecial-characteroperators(e.g.,
!
,
++
)
mustnothavespacenexttotheiroperand.

一元操作符(例如:!,++)在他们的下一个操作数之间不能包含空格。

Any
,
and
;
must
nothaveprecedingspace.

任何,和;的前面都不能包含空格。

Any
;
usedasastatementterminatormustbeattheendoftheline.

任何以;作为结尾的语句都要换行。

Any
:
afterapropertynameinanobjectdefinitionmustnothaveprecedingspace.

一个对象的属性名都必须紧跟:之间不能有空格。

The
?
and
:
in
aternaryconditionalmusthavespaceonbothsides.

三元操作符的?和:之间必须有空格。

Nofillerspacesinemptyconstructs(e.g.,
{}
,
[]
,
fn()
)

在无参构造函数的括号里面不能有空格(例如:
{}
,
[]
,
fn())


Newlineattheendofeachfile.

每一行结束后都要新起一行

Iftheentirefileiswrappedinaclosure,thefunctionbodyisnotindented.Seefullfileclosuresforexamples.

如果整个文件包在一个闭包,函数体不缩进。看到完整的文件关闭的例子。


linkBad
Examples

1

2

3

4
//Bad
if(condition)doSomething();
while(!condition)iterating++;
for(vari=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
vari=0;
if(condition){
doSomething();
}elseif(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(){
//Dostuff
},options);
foo(data,function(){
//Dostuff
});


linkObject
andArrayExpressions

Objectandarrayexpressionscanbeononelineiftheyareshort(rememberthelinelengthlimits).Whenanexpressionistoolongtofitononeline,theremustbeonepropertyorelementperline,withtheopeningandclosingbraceseachontheirownlines.
Propertynamesonlyneedtobequotediftheyarereservedwordsorcontainspecialcharacters:

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

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,"youare":15};
array=[9,
4,
15];
array=[{
key:val
}];
array=[{
key:val
},{
key2:val2
}];
//Good
map={ready:9,when:4,"youare":15};
array=[9,4,15];
array=[{key:val}];
array=[{key:val},{key2:val2}];
array=[
{key:val},
{key2:val2}
];
//Goodaswell
map={
ready:9,
when:4,
"youare":15
};
array=[
9,
4,
15
];
array=[
{
key:val
}
];
array=[
{
key:val
},
{
key2:val2
}
];


linkMulti-line
Statements

Whenastatementistoolongtofitononeline,linebreaksmustoccurafteranoperator.

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

1

2

3

4

5

6

7
//Bad
varhtml="<p>Thesumof"+a+"and"+b+"plus"+c
+"is"+(a+b+c);
//Good
varhtml="<p>Thesumof"+a+"and"+b+"plus"+c+
"is"+(a+b+c);

Linesshouldbebrokenintologicalgroupsifitimprovesreadability,suchassplittingeachexpressionofaternaryoperatorontoitsownlineevenifbothwillfitonasingleline.,

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

1

2

3
varbaz=firstCondition(foo)&&secondCondition(bar)?
qux(foo,bar):
foo;

Whenaconditionalistoolongtofitononeline,successivelinesmustbeindentedoneextraleveltodistinguishthemfromthebody.

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

1

2

3

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


linkChained
MethodCalls

Whenachainofmethodcallsistoolongtofitononeline,theremustbeonecallperline,withthefirstcallonaseparatelinefromtheobjectthemethodsarecalledon.Ifthemethodchangesthecontext,anextralevelofindentationmustbeused.

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

1

2

3

4

5

6
elements
.addClass("foo")
.children()
.html("hello")
.end()
.appendTo("body");


linkFull
FileClosures

Whenanentirefileiswrappedinaclosure,thebodyoftheclosureisnotindented.

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

1

2

3

4

5
(function($){
//Thisdoesn'tgetindented
})(jQuery);

1

2

3

4

5
module.exports=function(grunt){
//Thisdoesn'tgetindented
};

ThesameappliestoAMDwrappers.

这同样适用于AMD包装器。

1

2

3

4

5

6

7

8

9
define([
"foo",
"bar",
"baz"
],function(foo,bar,baz){
//Thisdoesn'tgetindented
});

ForUMD,thefactoryisindentedtovisuallydifferentiateitfromthebody.

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
(function(factory){
if(typeofdefine==="function"&&define.amd){
//AMD.Registerasananonymousmodule.
define([
"jquery"
],factory);
}else{
//Browserglobals
factory(jQuery);
}
}(function($){
//Thisdoesn'tgetindented
}));


linkConstructors

Constructorfunctionsshouldalwaysbeinvokedwithargumentlists,evenwhensuchlistsareempty.

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

1

2
thrownewError();
when=time||newDate();

Whenpropertyaccessormethodinvocationisimmediatelyperformedontheresultofaconstructorfunction,clarifyprecedencewithwrappingparentheses.

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

1

2
detachedMode=(newTemplateFactory(settings)).nodeType===11;
match=(newRegExp(pattern)).exec(input);


linkEquality

Strictequalitychecks(
===
)mustbeusedinfavorofabstractequalitychecks(
==
).
Theonlyexceptioniswhencheckingfor
undefined
and
null
by
wayof
null
.

严格的平等检查(===)必须使用支持抽象平等检查(==)。唯一的例外是当检查定义和空的空。

1

2
//Checkforbothundefinedandnullvalues,forsomeimportantreason.
undefOrNull==null;


linkType
Checks

String:
typeofobject==="string"


Number:
typeofobject==="number"


Boolean:
typeofobject==="boolean"


Object:
typeofobject==="object"


PlainObject:
jQuery.isPlainObject(object)


普通的对象


Function:
jQuery.isFunction(object)


函数


Array:
jQuery.isArray(object)


数组

Element:
object.nodeType


元素


null:
object===null


nullorundefined:
object==null


undefined:

GlobalVariables:
typeofvariable==="undefined"


全局变量:


LocalVariables:
variable===undefined


局部变量


Properties:
object.prop===undefined


属性



linkComments

Commentsarealwaysprecededbyablankline.Commentsstartwithacapitalfirstletter,butdon'trequireaperiodattheend,unlessyou'rewritingfullsentences.Theremustbeasinglespacebetweenthecommenttokenandthecommenttext.

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

Singlelinecommentsgooverthelinetheyreferto:

1

2

3

4

5

6
//Weneedanexplicit"bar",becauselaterinthecodefooischecked.
varfoo="bar";
//Evenlongcommentsthatspan
//multiplelinesusethesingle
//linecommentform.

Multi-linecommentsareonlyusedforfileandfunctionheaders.

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

Inlinecommentsareallowedasanexceptionwhenusedtoannotatespecialargumentsinformalparameterlistsorwhenneededtosupportaspecificdevelopmenttool:

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

1

2

3

4
functionfoo(types,selector,data,fn,/*INTERNAL*/one){
//Dostuff
}

DonotwriteAPIdocumentationincomments.APIdocumentationlivesinitsownrepository.

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


linkQuotes

jQueryusesdoublequotes.

jQuery使用双引号。

1
vardouble="Iamwrappedindoublequotes";

Stringsthatrequireinnerquotingmustusedoubleoutsideandsingleinside.

字符串,需要内部引用必须使用双外面和单里面。

1
varhtml="<divid='my-id'></div>";


linkSemicolons

Usethem.NeverrelyonASI.

分号

使用它们。不要依赖ASI。


linkNaming
Conventions

Variableandfunctionnamesshouldbefullwords,usingcamelcasewithalowercasefirstletter.Namesshouldbedescriptivebutnotexcessivelyso.Exceptionsareallowedforiterators,suchastheuseof
i
to
representtheindexinaloop.Constructorsdonotneedacapitalfirstletter.

命名约定

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


linkGlobal
Variables

Eachprojectmayexposeatmostoneglobalvariable.

全局变量

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


linkDOM
NodeRules

.nodeName
mustalwaysbeusedinfavorof
.tagName
.

DOM节点的规则

.nodeName必须使用支持.tagName。

.nodeType
mustbeusedtodeterminetheclassificationofanode(not
.nodeName
).

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


linkSwitch
Statements

Theusageof
switch
statementsisgenerallydiscouraged,butcanbeusefulwhenthere
arealargenumberofcases-especiallywhenmultiplecasescanbehandledbythesameblock,orfall-throughlogic(the
default
case)
canbeleveraged.

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

Whenusing
switch
statements:

Usea
break
foreachcaseotherthan
default
.

Align
case
statementswiththe
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();
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: