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

1 / 26
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功