您好,欢迎访问三七文档
当前位置:首页 > IT计算机/网络 > 数据库 > Google JavaScript Style Guide
link▽link▽link▽GoogleJavaScriptStyleGuideRevision2.11AaronWhyteBobJervisDanPupiusEricArvidssonFritzSchneiderRobbyWalkerEachstylepointhasasummaryforwhichadditionalinformationisavailablebytogglingtheaccompanyingarrowbuttonthatlooksthisway:▽.Youmaytoggleallsummarieswiththebigarrowbutton:▽ToggleallsummariesTableofContentsJavaScriptLanguageRulesvarConstantsSemicolonsNestedfunctionsFunctionDeclarationsWithinBlocksExceptionsCustomexceptionsStandardsfeaturesWrapperobjectsforprimitivetypesMulti-levelprototypehierarchiesMethoddefinitionsClosureseval()with(){}thisfor-inloopAssociativeArraysMultilinestringliteralsArrayandObjectliteralsModifyingprototypesofbuiltinobjectsInternetExplorer'sConditionalCommentsJavaScriptStyleRulesNamingCustomtoString()methodsDeferredinitializationExplicitscopeCodeformattingParenthesesStringsVisibility(privateandprotectedfields)JavaScriptTypesCommentsCompilingTipsandTricksImportantNoteDisplayingHiddenDetailsinthisGuideThisstyleguidecontainsmanydetailsthatareinitiallyhiddenfromview.Theyaremarkedbythetriangleicon,whichyouseehereonyourleft.Clickitnow.YoushouldseeHoorayappearbelow.Hooray!Nowyouknowyoucanexpandpointstogetmoredetails.Alternatively,there'satoggleallatthetopofthisdocument.BackgroundJavaScriptisthemainclient-sidescriptinglanguageusedbymanyofGoogle'sopen-sourceprojects.Thisstyleguideisalistofdosanddon'tsforJavaScriptprograms.JavaScriptLanguageRulesvarDeclarationswithvar:AlwaysDecision:Whenyoufailtospecifyvar,thevariablegetsplacedintheglobalcontext,potentiallyclobberingexistingvalues.Also,ifthere'snodeclaration,it'shardtotellinwhatscopeavariablelives(e.g.,itcouldbeintheDocumentorWindowjustaseasilyasinthelocalscope).Soalwaysdeclarewithvar.ConstantsUseNAMES_LIKE_THISforconstants.Use@constwhereappropriate.Neverusetheconstkeyword.Decision:Forsimpleprimitivevalueconstants,thenamingconventionisenough.link▽link▽/***Thenumberofsecondsinaminute.*@type{number}*/goog.example.SECONDS_IN_A_MINUTE=60;Fornon-primitives,usethe@constannotation./***Thenumberofsecondsineachofthegivenunits.*@type{Object.number}*@const*/goog.example.SECONDS_TABLE={minute:60,hour:60*60day:60*60*24}Thisallowsthecompilertoenforceconstant-ness.Asfortheconstkeyword,InternetExplorerdoesn'tparseit,sodon'tuseit.SemicolonsAlwaysusesemicolons.Relyingonimplicitinsertioncancausesubtle,hardtodebugproblems.Don'tdoit.You'rebetterthanthat.Thereareacoupleplaceswheremissingsemicolonsareparticularlydangerous://1.MyClass.prototype.myMethod=function(){return42;}//Nosemicolonhere.(function(){//Someinitializationcodewrappedinafunctiontocreateascopeforlocals.})();varx={'i':1,'j':2}//Nosemicolonhere.//2.TryingtodoonethingonInternetExplorerandanotheronFirefox.//Iknowyou'dneverwritecodelikethis,butthrowmeabone.[normalVersion,ffVersion][isIE]();varTHINGS_TO_EAT=[apples,oysters,sprayOnCheese]//Nosemicolonhere.//3.conditionalexecutionalabash-1==resultOfOperation()||die();Sowhathappens?1.JavaScripterror-firstthefunctionreturning42iscalledwiththesecondfunctionasaparameter,thenthenumber42iscalledresultinginanerror.2.Youwillmostlikelygeta'nosuchpropertyinundefined'erroratruntimeasittriestocallx[ffVersion][isIE]().3.dieiscalledunlessresultOfOperation()isNaNandTHINGS_TO_EATgetsassignedtheresultofdie().Why?JavaScriptrequiresstatementstoendwithasemicolon,exceptwhenitthinksitcansafelyinfertheirexistence.Ineachoftheseexamples,afunctiondeclarationorobjectorarrayliteralisusedinsideastatement.Theclosingbracketsarenotenoughtosignaltheendofthestatement.Javascriptneverendsastatementifthenexttokenisaninfixorbracketoperator.Thishasreallysurprisedpeople,somakesureyourassignmentsendwithsemicolons.NestedfunctionsYesNestedfunctionscanbeveryuseful,forexampleinthecreationofcontinuationsandforthetaskofhidinghelperfunctions.Feelfreetousethem.FunctionDeclarationsWithinBlockslink▽link▽link▽link▽link▽link▽NoDonotdothis:if(x){functionfoo(){}}WhilemostscriptenginessupportFunctionDeclarationswithinblocksitisnotpartofECMAScript(seeECMA-262,clause13and14).WorseimplementationsareinconsistentwitheachotherandwithfutureEcmaScriptproposals.ECMAScriptonlyallowsforFunctionDeclarationsintherootstatementlistofascriptorfunction.InsteaduseavariableinitializedwithaFunctionExpressiontodefineafunctionwithinablock:if(x){varfoo=function(){}}ExceptionsYesYoubasicallycan'tavoidexceptionsifyou'redoingsomethingnon-trivial(usinganapplicationdevelopmentframework,etc.).Goforit.CustomexceptionsYesWithoutcustomexceptions,returningerrorinformationfromafunctionthatalsoreturnsavaluecanbetricky,nottomentioninelegant.BadsolutionsincludepassinginareferencetypetoholderrorinformationoralwaysreturningObjectswithapotentialerrormember.Thesebasicallyamounttoaprimitiveexceptionhandlinghack.Feelfreetousecustomexceptionswhenappropriate.StandardsfeaturesAlwayspreferredovernon-standardsfeaturesFormaximumportabilityandcompatibility,alwayspreferstandardsfeaturesovernon-standardsfeatures(e.g.,string.charAt(3)overstring[3]andelementaccesswithDOMfunctionsinsteadofusinganapplication-specificshorthand).Wrapperobjectsforprimitivety
本文标题:Google JavaScript Style Guide
链接地址:https://www.777doc.com/doc-4605042 .html