Google JavaScript Style GuideWord格式.docx
- 文档编号:7399842
- 上传时间:2023-05-08
- 格式:DOCX
- 页数:63
- 大小:39.96KB
Google JavaScript Style GuideWord格式.docx
《Google JavaScript Style GuideWord格式.docx》由会员分享,可在线阅读,更多相关《Google JavaScript Style GuideWord格式.docx(63页珍藏版)》请在冰点文库上搜索。
ArrayandObjectliteralsModifyingprototypesofbuiltinobjects
InternetExplorer'
sConditionalComments
JavaScriptStyleRules
Naming
CustomtoString()methods
Deferredinitialization
Explicitscope
CodeformattingParentheses
Strings
Visibility(privateandprotectedfields)
JavaScriptTypes
CommentsCompiling
TipsandTricks
ImportantNote
DisplayingHiddenDetailsinthisGuide
link▽
Thisstyleguidecontainsmanydetailsthatareinitiallyhiddenfromview.Theyaremarkedbythetriangleicon,whichyouseehereonyourleft.Clickitnow.Youshouldsee"
Hooray"
appearbelow.
Hooray!
Nowyouknowyoucanexpandpointstogetmoredetails.Alternatively,there'
sa"
toggleall"
atthetopofthisdocument.
Background
JavaScriptisthemainclient-sidescriptinglanguageusedbymanyofGoogle'
sopen-sourceprojects.Thisstyleguideisalistof
dosand
don'
tsforJavaScriptprograms.
var
Declarationswith
var:
Always
Decision:
Whenyoufailtospecify
var,thevariablegetsplacedintheglobalcontext,potentiallyclobberingexistingvalues.Also,ifthere'
snodeclaration,it'
shardtotellinwhatscopeavariablelives(e.g.,itcouldbeintheDocumentorWindowjustaseasilyasinthelocalscope).Soalwaysdeclarewith
var.
Constants
>
Use
NAMES_LIKE_THIS
forconstants.Use
@const
whereappropriate.Neverusethe
const
keyword.
Forsimpleprimitivevalueconstants,thenamingconventionisenough.
/**
*Thenumberofsecondsinaminute.
*@type{number}
*/
goog.example.SECONDS_IN_A_MINUTE=60;
Fornon-primitives,usethe
annotation.
*Thenumberofsecondsineachofthegivenunits.
*@type{Object.<
number>
}
*@const
goog.example.SECONDS_TABLE={
minute:
60,
hour:
60*60
day:
60*60*24
Thisallowsthecompilertoenforceconstant-ness.
Asforthe
keyword,InternetExplorerdoesn'
tparseit,sodon'
tuseit.
Semicolons
Alwaysusesemicolons.
Relyingonimplicitinsertioncancausesubtle,hardtodebugproblems.Don'
tdoit.You'
rebetterthanthat.
Thereareacoupleplaceswheremissingsemicolonsareparticularlydangerous:
//1.
MyClass.prototype.myMethod=function(){
return42;
}//Nosemicolonhere.
(function(){
//Someinitializationcodewrappedinafunctiontocreateascopeforlocals.
})();
varx={
'
i'
:
1,
j'
2
//2.TryingtodoonethingonInternetExplorerandanotheronFirefox.
//Iknowyou'
dneverwritecodelikethis,butthrowmeabone.
[normalVersion,ffVersion][isIE]();
varTHINGS_TO_EAT=[apples,oysters,sprayOnCheese]//Nosemicolonhere.
//3.conditionalexecutionalabash
-1==resultOfOperation()||die();
Sowhathappens?
1.JavaScripterror-firstthefunctionreturning42iscalledwiththesecondfunctionasaparameter,thenthenumber42is"
called"
resultinginanerror.
2.Youwillmostlikelygeta'
nosuchpropertyinundefined'
erroratruntimeasittriestocall
x[ffVersion][isIE]().
3.die
iscalledunless
resultOfOperation()
is
NaN
and
THINGS_TO_EAT
getsassignedtheresultof
die().
Why?
JavaScriptrequiresstatementstoendwithasemicolon,exceptwhenitthinksitcansafelyinfertheirexistence.Ineachoftheseexamples,afunctiondeclarationorobjectorarrayliteralisusedinsideastatement.Theclosingbracketsarenotenoughtosignaltheendofthestatement.Javascriptneverendsastatementifthenexttokenisaninfixorbracketoperator.
Thishasreallysurprisedpeople,somakesureyourassignmentsendwithsemicolons.
Nestedfunctions
Yes
Nestedfunctionscanbeveryuseful,forexampleinthecreationofcontinuationsandforthetaskofhidinghelperfunctions.Feelfreetousethem.
FunctionDeclarationsWithinBlocks
No
Donotdothis:
if(x){
functionfoo(){}
WhilemostscriptenginessupportFunctionDeclarationswithinblocksitisnotpartofECMAScript(see
ECMA-262,clause13and14).WorseimplementationsareinconsistentwitheachotherandwithfutureEcmaScriptproposals.ECMAScriptonlyallowsforFunctionDeclarationsintherootstatementlistofascriptorfunction.InsteaduseavariableinitializedwithaFunctionExpressiontodefineafunctionwithinablock:
varfoo=function(){}
Exceptions
Youbasicallycan'
tavoidexceptionsifyou'
redoingsomethingnon-trivial(usinganapplicationdevelopmentframework,etc.).Goforit.
Customexceptions
Withoutcustomexceptions,returningerrorinformationfromafunctionthatalsoreturnsavaluecanbetricky,nottomentioninelegant.BadsolutionsincludepassinginareferencetypetoholderrorinformationoralwaysreturningObjectswithapotentialerrormember.Thesebasicallyamounttoaprimitiveexceptionhandlinghack.Feelfreetousecustomexceptionswhenappropriate.
Standardsfeatures
Alwayspreferredovernon-standardsfeatures
Formaximumportabilityandcompatibility,alwayspreferstandardsfeaturesovernon-standardsfeatures(e.g.,string.charAt(3)
over
string[3]
andelementaccesswithDOMfunctionsinsteadofusinganapplication-specificshorthand).
Wrapperobjectsforprimitivetypes
There'
snoreasontousewrapperobjectsforprimitivetypes,plusthey'
redangerous:
varx=newBoolean(false);
alert('
hi'
);
//Shows'
.
Don'
tdoit!
Howevertypecastingisfine.
varx=Boolean(0);
//Thiswillneverbealerted.
typeofBoolean(0)=='
boolean'
;
typeofnewBoolean(0)=='
object'
Thisisveryusefulforcastingthingsto
number,
string
boolean.
Multi-levelprototypehierarchies
Notpreferred
Multi-levelprototypehierarchiesarehowJavaScriptimplementsinheritance.Youhaveamulti-levelhierarchyifyouhaveauser-definedclassDwithanotheruser-definedclassBasitsprototype.Thesehierarchiesaremuchhardertogetrightthantheyfirstappear!
Forthatreason,itisbesttouse
goog.inherits()
from
theClosureLibrary
orsomethingsimilar.
functionD(){
goog.base(this)
goog.inherits(D,B);
D.prototype.method=function(){
...
};
Methoddefinitions
Foo.prototype.bar=function(){...};
Whilethereareseveralmethodsforattachingmethodsandpropertiestoaconstructor,thepreferredstyleis:
Foo.prototype.bar=function(){
/*...*/
Closures
Yes,butbecareful.
TheabilitytocreateclosuresisperhapsthemostusefulandoftenoverlookedfeatureofJS.Hereis
agooddescriptionofhowclosureswork
Onethingtokeepinmind,however,isthataclosurekeepsapointertoitsenclosingscope.Asaresult,attachingaclosuretoaDOMelementcancreateacircularreferenceandthus,amemoryleak.Forexample,inthefollowingcode:
functionfoo(element,a,b){
element.onclick=function(){/*usesaandb*/};
thefunctionclosurekeepsareferenceto
element,
a,and
b
evenifitneveruses
element.Since
element
alsokeepsareferencetotheclosure,wehaveacyclethatwon'
tbecleanedupbygarbagecollection.Inthesesituations,thecodecanbestructuredasfollows:
element.onclick=bar(a,b);
functionbar(a,b){
returnfunction(){/*usesaandb*/}
eval()
Onlyfordeserialization(e.g.evaluatingRPCresponses)
makesforconfusingsemanticsandisdangeroustouseifthestringbeing
eval()'
dcontainsuserinput.There'
susuallyabetter,moreclear,saferwaytowriteyourcode,soitsusedisgenerallynotpermitted.However
eval
makesdeserializationconsiderablyeasierthanthenon-eval
alternatives,soitsuseisacceptableforthistask(forexample,toevaluateRPCresponses).
Deserializationistheprocessoftransformingaseriesofbytesintoanin-memorydatastructure.Forexample,youmightwriteobjectsouttoafileas:
users=[
{
name:
Eric'
id:
37824,
email:
jellyvore@'
},
xtof'
31337,
b4d455h4x0r@'
];
Readingthesedatabackintomemoryisassimpleas
evalingthestringrepresentationofthefile.
Similarly,
cansimplifydecodingRPCreturnvalues.Forexample,youmightusean
XMLHttpRequest
tomakeanRPC,andinitsresponsetheservercanreturnJavaScript:
varuserOnline=false;
varuser='
nusrat'
varxmlhttp=newXMLHttpRequest();
xmlhttp.open('
GET'
'
+user,false);
xmlhttp.send('
'
//Serverreturns:
//userOnline=true;
if(xmlhttp.status==200){
eval(xmlhttp.responseText);
//userOnlineisnowtrue.
with(){}
Using
with
cloudsthesemanticsofyourprogram.Becausetheobjectofthe
canhavepropertiesthatcollidewithlocalvariables,itcandrasticallychangethemeaningofyourprogram.Forexample,whatdoesthisdo?
with(foo){
varx=3;
returnx;
Answer:
anything.Thelocalvariable
x
couldbeclobberedbyapropertyof
foo
andperhapsitevenhasasetter,inwhichcaseassigning
3
couldcauselotsof
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Google JavaScript Style Guide