1、Google JavaScript Style GuideGoogle JavaScript Style GuideRevision 2.11Aaron WhyteBob JervisDan PupiusEric ArvidssonFritz SchneiderRobby WalkerEach style point has a summary for which additional information is available by toggling the accompanying arrow button that looks this way:. You may toggle a
2、ll summaries with the big arrow button:Toggle all summariesTable of ContentsJavaScript Language RulesvarConstantsSemicolonsNested functionsFunction Declarations Within BlocksExceptionsCustom exceptionsStandards featuresWrapper objects for primitive typesMulti-level prototype hierarchiesMethod defini
3、tionsClosureseval()with() thisfor-in loopAssociative ArraysMultiline string literalsArray and Object literalsModifying prototypes of builtin objectsInternet Explorers Conditional CommentsJavaScript Style RulesNamingCustom toString() methodsDeferred initializationExplicit scopeCode formattingParenthe
4、sesStringsVisibility (private and protected fields)JavaScript TypesCommentsCompilingTips and TricksImportant NoteDisplaying Hidden Details in this GuidelinkThis style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you see here on your lef
5、t. Click it now. You should see Hooray appear below.Hooray! Now you know you can expand points to get more details. Alternatively, theres a toggle all at the top of this document.BackgroundJavaScript is the main client-side scripting language used by many of Googles open-source projects. This style
6、guide is a list ofdos anddonts for JavaScript programs.JavaScript Language RulesvarlinkDeclarations withvar: AlwaysDecision:When you fail to specifyvar, the variable gets placed in the global context, potentially clobbering existing values. Also, if theres no declaration, its hard to tell in what sc
7、ope a variable lives (e.g., it could be in the Document or Window just as easily as in the local scope). So always declare withvar.ConstantslinkUseNAMES_LIKE_THISfor constants. Useconstwhere appropriate. Never use theconstkeyword.Decision:For simple primitive value constants, the naming convention i
8、s enough./* * The number of seconds in a minute. * type number */goog.example.SECONDS_IN_A_MINUTE = 60;For non-primitives, use theconstannotation./* * The number of seconds in each of the given units. * type Object. * const */goog.example.SECONDS_TABLE = minute: 60, hour: 60 * 60 day: 60 * 60 * 24Th
9、is allows the compiler to enforce constant-ness.As for theconstkeyword, Internet Explorer doesnt parse it, so dont use it.SemicolonslinkAlways use semicolons.Relying on implicit insertion can cause subtle, hard to debug problems. Dont do it. Youre better than that.There are a couple places where mis
10、sing semicolons are particularly dangerous:/ 1.MyClass.prototype.myMethod = function() return 42; / No semicolon here.(function() / Some initialization code wrapped in a function to create a scope for locals.)();var x = i: 1, j: 2 / No semicolon here./ 2. Trying to do one thing on Internet Explorer
11、and another on Firefox./ I know youd never write code like this, but throw me a bone.normalVersion, ffVersionisIE();var THINGS_TO_EAT = apples, oysters, sprayOnCheese / No semicolon here./ 3. conditional execution a la bash-1 = resultOfOperation() | die();So what happens?1. JavaScript error - first
12、the function returning 42 is called with the second function as a parameter, then the number 42 is called resulting in an error.2. You will most likely get a no such property in undefined error at runtime as it tries to callxffVersionisIE().3. dieis called unlessresultOfOperation()isNaNandTHINGS_TO_
13、EATgets assigned the result ofdie().Why?JavaScript requires statements to end with a semicolon, except when it thinks it can safely infer their existence. In each of these examples, a function declaration or object or array literal is used inside a statement. The closing brackets are not enough to s
14、ignal the end of the statement. Javascript never ends a statement if the next token is an infix or bracket operator.This has really surprised people, so make sure your assignments end with semicolons.Nested functionslinkYesNested functions can be very useful, for example in the creation of continuat
15、ions and for the task of hiding helper functions. Feel free to use them.Function Declarations Within BlockslinkNoDo not do this:if (x) function foo() While most script engines support Function Declarations within blocks it is not part of ECMAScript (seeECMA-262, clause 13 and 14). Worse implementati
16、ons are inconsistent with each other and with future EcmaScript proposals. ECMAScript only allows for Function Declarations in the root statement list of a script or function. Instead use a variable initialized with a Function Expression to define a function within a block:if (x) var foo = function(
17、) ExceptionslinkYesYou basically cant avoid exceptions if youre doing something non-trivial (using an application development framework, etc.). Go for it.Custom exceptionslinkYesWithout custom exceptions, returning error information from a function that also returns a value can be tricky, not to men
18、tion inelegant. Bad solutions include passing in a reference type to hold error information or always returning Objects with a potential error member. These basically amount to a primitive exception handling hack. Feel free to use custom exceptions when appropriate.Standards featureslinkAlways prefe
19、rred over non-standards featuresFor maximum portability and compatibility, always prefer standards features over non-standards features (e.g.,string.charAt(3)overstring3and element access with DOM functions instead of using an application-specific shorthand).Wrapper objects for primitive typeslinkNo
20、Theres no reason to use wrapper objects for primitive types, plus theyre dangerous:var x = new Boolean(false);if (x) alert(hi); / Shows hi.Dont do it!However type casting is fine.var x = Boolean(0);if (x) alert(hi); / This will never be alerted.typeof Boolean(0) = boolean;typeof new Boolean(0) = obj
21、ect;This is very useful for casting things tonumber,stringandboolean.Multi-level prototype hierarchieslinkNot preferredMulti-level prototype hierarchies are how JavaScript implements inheritance. You have a multi-level hierarchy if you have a user-defined class D with another user-defined class B as
22、 its prototype. These hierarchies are much harder to get right than they first appear!For that reason, it is best to usegoog.inherits()fromthe Closure Libraryor something similar.function D() goog.base(this)goog.inherits(D, B);D.prototype.method = function() .;Method definitionslinkFoo.prototype.bar
23、 = function() . ;While there are several methods for attaching methods and properties to a constructor, the preferred style is:Foo.prototype.bar = function() /* . */;ClosureslinkYes, but be careful.The ability to create closures is perhaps the most useful and often overlooked feature of JS. Here isa
24、 good description of how closures work.One thing to keep in mind, however, is that a closure keeps a pointer to its enclosing scope. As a result, attaching a closure to a DOM element can create a circular reference and thus, a memory leak. For example, in the following code:function foo(element, a,
25、b) element.onclick = function() /* uses a and b */ ;the function closure keeps a reference toelement,a, andbeven if it never useselement. Sinceelementalso keeps a reference to the closure, we have a cycle that wont be cleaned up by garbage collection. In these situations, the code can be structured
26、as follows:function foo(element, a, b) element.onclick = bar(a, b);function bar(a, b) return function() /* uses a and b */ eval()linkOnly for deserialization (e.g. evaluating RPC responses)eval()makes for confusing semantics and is dangerous to use if the string beingeval()d contains user input. The
27、res usually a better, more clear, safer way to write your code, so its used is generally not permitted. Howeverevalmakes deserialization considerably easier than the non-evalalternatives, so its use is acceptable for this task (for example, to evaluate RPC responses).Deserialization is the process o
28、f transforming a series of bytes into an in-memory data structure. For example, you might write objects out to a file as:users = name: Eric, id: 37824, email: jellyvore , name: xtof, id: 31337, email: b4d455h4x0r , .;Reading these data back into memory is as simple asevaling the string representatio
29、n of the file.Similarly,eval()can simplify decoding RPC return values. For example, you might use anXMLHttpRequestto make an RPC, and in its response the server can return JavaScript:var userOnline = false;var user = nusrat;var xmlhttp = new XMLHttpRequest();xmlhttp.open(GET, + user, false);xmlhttp.
30、send();/ Server returns:/ userOnline = true;if (xmlhttp.status = 200) eval(xmlhttp.responseText);/ userOnline is now true.with() linkNoUsingwithclouds the semantics of your program. Because the object of thewithcan have properties that collide with local variables, it can drastically change the meaning of your program. For example, what does this do?with (foo) var x = 3; return x;Answer: anything. The local variablexcould be clobbered by a property offooand perhaps it even has a setter, in which case assigning3could cause lots of
copyright@ 2008-2023 冰点文库 网站版权所有
经营许可证编号:鄂ICP备19020893号-2