1
<?xml version = '1.0'?>
2
<?xml-stylesheet type="text/xsl" href="styleguide.xsl"?>
3
<GUIDE title="Google JavaScript Style Guide">
18
<CATEGORY title="Important Note">
19
<STYLEPOINT title="Displaying Hidden Details in this Guide">
21
This style guide contains many details that are initially
22
hidden from view. They are marked by the triangle icon, which you
23
see here on your left. Click it now.
24
You should see "Hooray" appear below.
28
Hooray! Now you know you can expand points to get more
29
details. Alternatively, there's a "toggle all" at the
35
<CATEGORY title="Background">
37
JavaScript is the main client-side scripting language used
39
by many of Google's open-source
41
This style guide is a list of <em>do</em>s and <em>don't</em>s for
49
<CATEGORY title="JavaScript Language Rules">
52
<STYLEPOINT title="var">
54
Declarations with <code>var</code>: Always
58
When you fail to specify <code>var</code>,
59
the variable gets placed in the global context, potentially clobbering
60
existing values. Also, if there's no declaration, it's hard to tell in
61
what scope a variable lives (e.g., it could be in the Document or
62
Window just as easily as in the local scope). So always declare with
68
<STYLEPOINT title="Constants">
70
>Use <code>NAMES_LIKE_THIS</code> for constants.
71
Use <code>@const</code> where appropriate.
72
Never use the <code>const</code> keyword.
76
<p>For simple primitive value constants, the naming convention is
80
* The number of seconds in a minute.
83
goog.example.SECONDS_IN_A_MINUTE = 60;
85
<p>For non-primitives, use the <code>@const</code> annotation.</p>
88
* The number of seconds in each of the given units.
89
* @type {Object.<number>}
92
goog.example.SECONDS_TABLE = {
98
<p>This allows the compiler to enforce constant-ness.</p>
99
<p>As for the <code>const</code> keyword, Internet Explorer doesn't
100
parse it, so don't use it.</p>
105
<STYLEPOINT title="Semicolons">
107
Always use semicolons.
110
<p>Relying on implicit insertion can cause subtle, hard to debug
111
problems. Don't do it. You're better than that.</p>
112
<p>There are a couple places where missing semicolons are particularly
116
MyClass.prototype.myMethod = function() {
118
} // No semicolon here.
121
// Some initialization code wrapped in a function to create a scope for locals.
128
} // No semicolon here.
130
// 2. Trying to do one thing on Internet Explorer and another on Firefox.
131
// I know you'd never write code like this, but throw me a bone.
132
[normalVersion, ffVersion][isIE]();
135
var THINGS_TO_EAT = [apples, oysters, sprayOnCheese] // No semicolon here.
137
// 3. conditional execution a la bash
138
-1 == resultOfOperation() || die();
140
<SUBSECTION title="So what happens?">
142
<li>JavaScript error - first the function returning 42 is called
143
with the second function as a parameter, then the number 42 is
144
"called" resulting in an error.</li>
145
<li>You will most likely get a 'no such property in undefined'
146
error at runtime as it tries to call
147
<code>x[ffVersion][isIE]()</code>.</li>
148
<li><code>die</code> is called unless
149
<code>resultOfOperation()</code> is <code>NaN</code> and
150
<code>THINGS_TO_EAT</code> gets assigned the result of
151
<code>die()</code>.</li>
154
<SUBSECTION title="Why?">
155
<p>JavaScript requires statements to end with a semicolon,
156
except when it thinks it can safely infer their existence. In each
157
of these examples, a function declaration or object or array literal
158
is used inside a statement. The closing brackets are not enough to
159
signal the end of the statement. Javascript never ends a statement
160
if the next token is an infix or bracket operator.</p>
161
<p>This has really surprised people, so make sure your assignments end
167
<STYLEPOINT title="Nested functions">
168
<SUMMARY>Yes</SUMMARY>
170
<p>Nested functions can be very useful, for example in the creation of
171
continuations and for the task of hiding helper functions. Feel free
176
<STYLEPOINT title="Exceptions">
177
<SUMMARY>Yes</SUMMARY>
179
<p>You basically can't avoid exceptions if you're doing something
180
non-trivial (using an application development framework, etc.).
185
<STYLEPOINT title="Custom exceptions">
186
<SUMMARY>Yes</SUMMARY>
188
<p>Without custom exceptions, returning error information from a
189
function that also returns a value can be tricky, not to mention
190
inelegant. Bad solutions include passing in a reference type to hold
191
error information or always returning Objects with a potential
192
error member. These basically amount to a primitive exception
193
handling hack. Feel free to use custom exceptions when
198
<STYLEPOINT title="Standards features">
199
<SUMMARY>Always preferred over non-standards features</SUMMARY>
201
<p>For maximum portability and compatibility, always prefer standards
202
features over non-standards features (e.g.,
203
<code>string.charAt(3)</code> over <code>string[3]</code> and element
204
access with DOM functions instead of using an application-specific
209
<STYLEPOINT title="Wrapper objects for primitive types">
210
<SUMMARY>No</SUMMARY>
212
<p>There's no reason to use wrapper objects for primitive types, plus
213
they're dangerous:</p>
215
var x = new Boolean(false);
217
alert('hi'); // Shows 'hi'.
221
<p>However type casting is fine.</p>
225
alert('hi'); // This will never be alerted.
227
typeof Boolean(0) == 'boolean';
228
typeof new Boolean(0) == 'object';
230
<p>This is very useful for casting things to
231
<code>number</code>, <code>string</code> and <code>boolean</code>.</p>
235
<STYLEPOINT title="Multi-level prototype hierarchies">
236
<SUMMARY>Not preferred</SUMMARY>
238
<p>Multi-level prototype hierarchies are how JavaScript implements
239
inheritance. You have a multi-level hierarchy if you have a
240
user-defined class D with another user-defined class B as its
241
prototype. These hierarchies are much harder to get right than they
244
<p>For that reason, it is best to use <code>goog.inherits()</code> from
245
<a href="http://code.google.com/closure/library/">
248
or something similar.
257
D.prototype.method = function() {
264
<STYLEPOINT title="Method definitions">
265
<SUMMARY><code>Foo.prototype.bar = function() { ... };</code></SUMMARY>
267
<p>While there are several methods for attaching methods and
268
properties to a constructor, the preferred style is:</p>
270
Foo.prototype.bar = function() {
277
<STYLEPOINT title="Closures">
278
<SUMMARY>Yes, but be careful.</SUMMARY>
280
<p>The ability to create closures is perhaps the most useful and often
281
overlooked feature of JS. Here is
282
<a href="http://jibbering.com/faq/faq_notes/closures.html">
283
a good description of how closures work
285
<p>One thing to keep in mind, however, is that a closure keeps a pointer
286
to its enclosing scope. As a result, attaching a closure to a DOM
287
element can create a circular reference and thus, a memory leak. For
288
example, in the following code:</p>
290
function foo(element, a, b) {
291
element.onclick = function() { /* uses a and b */ };
294
<p>the function closure keeps a reference to <code>element</code>,
295
<code>a</code>, and <code>b</code> even if it never uses
296
<code>element</code>. Since <code>element</code> also keeps a
297
reference to the closure, we have a cycle that won't be cleaned up by
298
garbage collection. In these situations, the code can be structured
301
function foo(element, a, b) {
302
element.onclick = bar(a, b);
306
return function() { /* uses a and b */ }
312
<STYLEPOINT title="eval()">
314
Only for deserialization (e.g. evaluating RPC responses)
317
<p><code>eval()</code> makes for confusing semantics and is dangerous
318
to use if the string being <code>eval()</code>'d contains user input.
319
There's usually a better, more clear, safer way to write your code, so
320
its used is generally not permitted. However <code>eval</code> makes
321
deserialization considerably easier than the non-<code>eval</code>
322
alternatives, so its use is acceptable for this task (for example, to
323
evaluate RPC responses).</p>
324
<p>Deserialization is the process of transforming a series of bytes into
325
an in-memory data structure. For example, you might write objects out
332
email: 'jellyvore@myway.com'
337
email: 'b4d455h4x0r@google.com'
342
<p>Reading these data back into memory is as simple as
343
<code>eval</code>ing the string representation of the file.</p>
344
<p>Similarly, <code>eval()</code> can simplify decoding RPC return
345
values. For example, you might use an <code>XMLHttpRequest</code>
346
to make an RPC, and in its response the server can return
349
var userOnline = false;
351
var xmlhttp = new XMLHttpRequest();
352
xmlhttp.open('GET', 'http://chat.google.com/isUserOnline?user=' + user, false);
355
// userOnline = true;
356
if (xmlhttp.status == 200) {
357
eval(xmlhttp.responseText);
359
// userOnline is now true.
364
<STYLEPOINT title="with() {}">
365
<SUMMARY>No</SUMMARY>
367
<p>Using <code>with</code> clouds the semantics of your program.
368
Because the object of the <code>with</code> can have properties that
369
collide with local variables, it can drastically change the meaning
370
of your program. For example, what does this do?</p>
377
<p>Answer: anything. The local variable <code>x</code> could be
378
clobbered by a property of <code>foo</code> and perhaps it even has
379
a setter, in which case assigning <code>3</code> could cause lots of
380
other code to execute. Don't use <code>with</code>.</p>
384
<STYLEPOINT title="this">
386
Only in object constructors, methods, and in setting up closures
389
<p>The semantics of <code>this</code> can be tricky. At times it refers
390
to the global object (in most places), the scope of the caller (in
391
<code>eval</code>), a node in the DOM tree (when attached using an
392
event handler HTML attribute), a newly created object (in a
393
constructor), or some other object (if function was
394
<code>call()</code>ed or <code>apply()</code>ed).</p>
395
<p>Because this is so easy to get wrong, limit its use to those places
396
where it is required:</p>
398
<li>in constructors</li>
399
<li>in methods of objects (including in the creation of closures)</li>
404
<STYLEPOINT title="for-in loop">
406
Only for iterating over keys in an object/map/hash
409
<p><code>for-in</code> loops are often incorrectly used to loop over
410
the elements in an <code>Array</code>. This is however very error
411
prone because it does not loop from <code>0</code> to
412
<code>length - 1</code> but over all the present keys in the object
413
and its prototype chain. Here are a few cases where it fails:</p>
415
function printArray(arr) {
416
for (var key in arr) {
421
printArray([0,1,2,3]); // This works.
423
var a = new Array(10);
424
printArray(a); // This is wrong.
426
a = document.getElementsByTagName('*');
427
printArray(a); // This is wrong.
431
printArray(a); // This is wrong again.
435
printArray(a); // This is wrong again.
437
<p>Always use normal for loops when using arrays.</p>
439
function printArray(arr) {
441
for (var i = 0; i < l; i++) {
449
<STYLEPOINT title="Associative Arrays">
451
Never use <code>Array</code> as a map/hash/associative array
454
<p>Associative <code>Array</code>s are not allowed... or more precisely
455
you are not allowed to use non number indexes for arrays. If you need
456
a map/hash use <code>Object</code> instead of <code>Array</code> in
457
these cases because the features that you want are actually features
458
of <code>Object</code> and not of <code>Array</code>.
459
<code>Array</code> just happens to extend <code>Object</code> (like
460
any other object in JS and therefore you might as well have used
461
<code>Date</code>, <code>RegExp</code> or <code>String</code>).</p>
465
<STYLEPOINT title="Multiline string literals">
466
<SUMMARY>No</SUMMARY>
468
<p>Do not do this:</p>
470
var myString = 'A rather long string of English text, an error message \
471
actually that just keeps going and going -- an error \
472
message to make the Energizer bunny blush (right through \
473
those Schwarzenegger shades)! Where was I? Oh yes, \
474
you\'ve got an error and all the extraneous whitespace is \
475
just gravy. Have a nice day.';
477
<p>The whitespace at the beginning of each line can't be safely stripped
478
at compile time; whitespace after the slash will result in tricky
479
errors; and while most script engines support this, it is not part
484
<STYLEPOINT title="Array and Object literals">
485
<SUMMARY>Yes</SUMMARY>
487
<p>Use <code>Array</code> and <code>Object</code> literals instead of
488
<code>Array</code> and <code>Object</code> constructors.</p>
489
<p>Array constructors are error-prone due to their arguments.</p>
492
var a1 = new Array(x1, x2, x3);
495
var a2 = new Array(x1, x2);
497
// If x1 is a number and it is a natural number the length will be x1.
498
// If x1 is a number but not a natural number this will throw an exception.
499
// Otherwise the array will have one element with x1 as its value.
500
var a3 = new Array(x1);
503
var a4 = new Array();
505
<p>Because of this, if someone changes the code to pass 1 argument
506
instead of 2 arguments, the array might not have the expected
508
<p>To avoid these kinds of weird cases, always use the more readable
511
var a = [x1, x2, x3];
516
<p>Object constructors don't have the same problems, but for readability
517
and consistency object literals should be used.</p>
519
var o = new Object();
521
var o2 = new Object();
525
o2['strange key'] = 3;
527
<p>Should be written as:</p>
541
<STYLEPOINT title="Modifying prototypes of builtin objects">
542
<SUMMARY>No</SUMMARY>
544
<p>Modifying builtins like <code>Object.prototype</code> and
545
<code>Array.prototype</code> are strictly forbidden. Modifying other
546
builtins like <code>Function.prototype</code> is less dangerous but
547
still leads to hard to debug issues in production and should be
553
<CATEGORY title="JavaScript Style Rules">
554
<STYLEPOINT title="Naming">
556
<p>In general, use <code>functionNamesLikeThis</code>,
557
<code>variableNamesLikeThis</code>, <code>ClassNamesLikeThis</code>,
558
<code>EnumNamesLikeThis</code>, <code>methodNamesLikeThis</code>,
559
and <code>SYMBOLIC_CONSTANTS_LIKE_THIS</code>.</p>
560
<p>Expand for more information.</p>
563
<SUBSECTION title="Properties and methods">
565
<li><em>Private</em> properties, variables, and methods (in files
566
or classes) should be named with a trailing
569
<li><em>Protected</em> properties, variables, and methods should be
570
named without a trailing underscore (like public ones).</li>
572
<p>For more information on <em>private</em> and <em>protected</em>,
574
<a href="#Visibility__private_and_protected_fields_">
579
<SUBSECTION title="Method and function parameter">
580
<p>Optional function arguments start with <code>opt_</code>.</p>
581
<p>Functions that take a variable number of arguments should have the
582
last argument named <code>var_args</code>. You may not refer to
583
<code>var_args</code> in the code; use the <code>arguments</code>
585
<p>Optional and variable arguments can also be specified in
586
<code>@param</code> annotations. Although either convention is
587
acceptable to the compiler, using both together is preferred.</p>
591
<SUBSECTION title="Getters and Setters">
592
<p>Getters and setters for properties are not required. However, if
593
they are used, then getters must be named <code>getFoo()</code> and
594
setters must be named <code>setFoo(value)</code>. (For boolean
595
getters, <code>isFoo()</code> is also acceptable, and often sounds
599
<SUBSECTION title="Namespaces">
600
<p>JavaScript has no inherent packaging or namespacing support.</p>
601
<p>Global name conflicts are difficult to debug, and can cause
602
intractable problems when two projects try to integrate. In order
603
to make it possible to share common JavaScript code, we've adopted
604
conventions to prevent collisions. </p>
605
<SUBSUBSECTION title="Use namespaces for global code">
606
<p><em>ALWAYS</em> prefix identifiers in the global scope with a
607
unique pseudo namespace related to the project or library. If you
608
are working on "Project Sloth", a reasonable pseudo namespace
609
would be <code>sloth.*</code>.</p>
613
sloth.sleep = function() {
619
<p>Many JavaScript libraries, including
620
<a href="http://code.google.com/closure/library/">
624
<a href="http://www.dojotoolkit.org/">
627
give you high-level functions for declaring your namespaces.
628
Be consistent about how you declare your namespaces.</p>
630
goog.provide('sloth');
632
sloth.sleep = function() {
637
<SUBSUBSECTION title="Respect namespace ownership">
638
<p>When choosing a child-namespace, make sure that the owners of the
639
parent namespace know what you are doing. If you start a project
640
that creates hats for sloths, make sure that the Sloth team knows
641
that you're using <code>sloth.hats</code>.</p>
644
<SUBSUBSECTION title="Use different namespaces for external code and internal code">
645
<p>"External code" is code that comes from outside your codebase,
646
and is compiled independently. Internal and external names should
647
be kept strictly separate. If you're using an external library
648
that makes things available in <code>foo.hats.*</code>, your
649
internal code should not define all its symbols in
650
<code>foo.hats.*</code>, because it will break if the other
651
team defines new symbols.</p>
653
foo.require('foo.hats');
656
* WRONG -- Do NOT do this.
658
* @extend {foo.hats.RoundHat}
660
foo.hats.BowlerHat = function() {
663
<p>If you need to define new APIs on an external namespace, then you
664
should explicitly export the public API functions, and only those
665
functions. Your internal code should call the internal APIs by
666
their internal names, for consistency and so that the compiler
667
can optimize them better.</p>
669
foo.provide('googleyhats.BowlerHat');
671
foo.require('foo.hats');
675
* @extend {foo.hats.RoundHat}
677
googleyhats.BowlerHat = function() {
681
goog.exportSymbol('foo.hats.BowlerHat', googleyhats.BowlerHat);
687
<SUBSECTION title="Filenames">
688
<p>Filenames should be all lowercase in order to avoid confusion on
689
case-sensitive platforms. Filenames should end in <code>.js</code>,
690
and should contain no punctuation except for <code>-</code> or
691
<code>_</code> (prefer <code>-</code> to <code>_</code>).</p>
697
<STYLEPOINT title="Custom toString() methods">
699
Must always succeed without side effects.
702
<p>You can control how your objects string-ify themselves by defining a
703
custom <code>toString()</code> method. This is fine, but you need
704
to ensure that your method (1) always succeeds and (2) does not have
705
side-effects. If your method doesn't meet these criteria, it's very
706
easy to run into serious problems. For example, if
707
<code>toString()</code> calls a method that does an
708
<code>assert</code>, <code>assert</code> might try to output the name
709
of the object in which it failed, which of course requires calling
710
<code>toString()</code>.</p>
714
<STYLEPOINT title="Deferred initialization">
715
<SUMMARY>OK</SUMMARY>
717
<p>It isn't always possible to initialize variables at the point of
718
declaration, so deferred initialization is fine.</p>
722
<STYLEPOINT title="Explicit scope">
723
<SUMMARY>Always</SUMMARY>
725
<p>Always use explicit scope - doing so increases portability and
726
clarity. For example, don't rely on <code>window</code> being in the
727
scope chain. You might want to use your function in another
728
application for which <code>window</code> is not the content
733
<STYLEPOINT title="Code formatting">
734
<SUMMARY>Expand for more info.</SUMMARY>
736
<p>We follow the <a href="cppguide.xml#Formatting">C++ formatting
737
rules</a> in spirit, with the following additional clarifications.</p>
738
<SUBSECTION title="Curly Braces">
739
<p>Because of implicit semicolon insertion, always start your curly
740
braces on the same line as whatever they're opening. For
750
<SUBSECTION title="Array and Object Initializers">
751
<p>Single-line array and object initializers are allowed when they
754
var arr = [1, 2, 3]; // No space after [ or before ].
755
var obj = {a: 1, b: 2, c: 3}; // No space after { or before }.
757
<p>Multiline array initializers and object initializers are indented
758
2 spaces, just like blocks.</p>
760
// Object initializer.
768
// Array initializer.
770
'"Slartibartfast" <fjordmaster@magrathea.com>',
771
'"Zaphod Beeblebrox" <theprez@universe.gov>',
772
'"Ford Prefect" <ford@theguide.com>',
773
'"Arthur Dent" <has.no.tea@gmail.com>',
774
'"Marvin the Paranoid Android" <marv@googlemail.com>',
775
'the.mice@magrathea.com'
778
// Used in a method call.
779
goog.dom.createDom(goog.dom.TagName.DIV, {
781
className: 'some-css-class',
782
style: 'display:none'
785
<p>Long identifiers or values present problems for aligned
786
initialization lists, so always prefer non-aligned initialization.
789
CORRECT_Object.prototype = {
795
<p>Not like this:</p>
797
WRONG_Object.prototype = {
804
<SUBSECTION title="Function Arguments">
805
<p>When possible, all function arguments should be listed on the same
806
line. If doing so would exceed the 80-column limit, the arguments
807
must be line-wrapped in a readable way. To save space, you may wrap
808
as close to 80 as possible, or put each argument on its own line to
809
enhance readability. The indentation may be either four spaces, or
810
aligned to the parenthesis. Below are the most common patterns for
811
argument wrapping:</p>
813
// Four-space, wrap at 80. Works with very long function names, survives
814
// renaming without reindenting, low on space.
815
goog.foo.bar.doThingThatIsVeryDifficultToExplain = function(
816
veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,
817
tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {
821
// Four-space, one argument per line. Works with long function names,
822
// survives renaming, and emphasizes each argument.
823
goog.foo.bar.doThingThatIsVeryDifficultToExplain = function(
824
veryDescriptiveArgumentNumberOne,
825
veryDescriptiveArgumentTwo,
826
tableModelEventHandlerProxy,
827
artichokeDescriptorAdapterIterator) {
831
// Parenthesis-aligned indentation, wrap at 80. Visually groups arguments,
833
function foo(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,
834
tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {
838
// Parenthesis-aligned, one argument per line. Visually groups and
839
// emphasizes each individual argument.
840
function bar(veryDescriptiveArgumentNumberOne,
841
veryDescriptiveArgumentTwo,
842
tableModelEventHandlerProxy,
843
artichokeDescriptorAdapterIterator) {
848
<SUBSECTION title="Passing Anonymous Functions">
849
<p>When declaring an anonymous function in the list of arguments for
850
a function call, the body of the function is indented two spaces
851
from the left edge of the function call or the statement, not two
852
spaces from the left edge of the function keyword. This is to make
853
the body of the anonymous function easier to read (i.e. not be all
854
squished up into the right half of the screen).</p>
856
var names = items.map(function(item) {
860
prefix.something.reallyLongFunctionName('whatever', function(a1, a2) {
862
someOtherLongFunctionName(a1);
864
andNowForSomethingCompletelyDifferent(a2.parrot);
869
<SUBSECTION title="More Indentation">
870
<p>In fact, except for
871
<a href="#Array_and_Object_literals">
872
array and object initializers
873
</a>, and passing anonymous functions, all wrapped lines
874
should be indented either left-aligned to the expression above, or
875
indented four spaces, not indented two spaces.</p>
878
someWonderfulHtml = '<div class="' + getClassesForWonderfulHtml()'">' +
879
getEvenMoreHtml(someReallyInterestingValues, moreValues,
880
evenMoreParams, 'a duck', true, 72,
881
slightlyMoreMonkeys(0xfff)) +
884
thisIsAVeryLongVariableName =
885
hereIsAnEvenLongerOtherFunctionNameThatWillNotFitOnPrevLine();
887
thisIsAVeryLongVariableName = 'expressionPartOne' + someMethodThatIsLong() +
888
thisIsAnEvenLongerOtherFunctionNameThatCannotBeIndentedMore();
890
someValue = this.foo(
892
'Some really long string arg - this is a pretty common case, actually.',
896
if (searchableCollection(allYourStuff).contains(theStuffYouWant) &&
897
!ambientNotification.isActive() && (client.isAmbientSupported() ||
898
client.alwaysTryAmbientAnyways()) {
899
ambientNotification.activate();
903
<SUBSECTION title="Blank lines">
904
<p>Use newlines to group logically related pieces of code.
908
doSomethingElseTo(x);
911
nowDoSomethingWith(y);
916
<SUBSECTION title="Binary and Ternary Operators">
917
<p>Always put the operator on the preceding line, so that you don't
918
have to think about implicit semi-colon insertion issues. Otherwise,
919
line breaks and indentation follow the same rules as in other
920
Google style guides.</p>
922
var x = a ? b : c; // All on one line if it will fit.
924
// Indentation +4 is OK.
926
longButSimpleOperandB : longButSimpleOperandC;
928
// Indenting to the line position of the first operand is also OK.
937
<STYLEPOINT title="Parentheses">
938
<SUMMARY>Only where required</SUMMARY>
940
<p>Use sparingly and in general only where required by the syntax
942
<p>Never use parentheses for unary operators such as
943
<code>delete</code>, <code>typeof</code> and <code>void</code> or
944
after keywords such as <code>return</code>, <code>throw</code> as
945
well as others (<code>case</code>, in or <code>new</code>).</p>
949
<STYLEPOINT title="Strings">
950
<SUMMARY>Prefer ' over "</SUMMARY>
952
<p>For consistency single-quotes (') are preferred to double-quotes (").
953
This is helpful when creating strings that include HTML:</p>
955
var msg = 'This is <a href="http://foo">some HTML</a>';
960
<STYLEPOINT title="Visibility (private and protected fields)">
961
<SUMMARY>Encouraged, use JSDoc annotations <code>@private</code> and
962
<code>@protected</code></SUMMARY>
964
<p>We recommend the use of the JSDoc annotations <code>@private</code> and
965
<code>@protected</code> to indicate visibility levels for classes,
966
functions, and properties.</p>
968
<p><code>@private</code> global variables and functions are only
969
accessible to code in the same file.</p>
970
<p>Constructors marked <code>@private</code> may only be instantiated by
971
code in the same file and by their static and instance members.
972
<code>@private</code> constructors may also be accessed anywhere in the
973
same file for their public static properties and by the
974
<code>instanceof</code> operator.</p>
975
<p>Global variables, functions, and constructors should never be
976
annotated <code>@protected</code>.</p>
979
// AA_PrivateClass_ and AA_init_ are accessible because they are global
980
// and in the same file.
986
AA_PrivateClass_ = function() {
990
function AA_init_() {
991
return new AA_PrivateClass_();
996
<p><code>@private</code> properties are accessible to all code in the
997
same file, plus all static methods and instance methods of that class
998
that "owns" the property, if the property belongs to a class. They
999
cannot be accessed or overridden from a subclass in a different file.</p>
1000
<p><code>@protected</code> properties are accessible to all code in the
1001
same file, plus any static methods and instance methods of any subclass
1002
of a class that "owns" the property.</p>
1003
<p>Note that these semantics differ from those of C++ and Java, in that
1004
they grant private and protected access to all code in the same file,
1005
not just in the same class or class hierarchy. Also, unlike in C++,
1006
private properties cannot be overriden by a subclass.
1012
AA_PublicClass = function() {
1016
AA_PublicClass.staticPrivateProp_ = 1;
1019
AA_PublicClass.prototype.privateProp_ = 2;
1022
AA_PublicClass.staticProtectedProp = 31;
1025
AA_PublicClass.prototype.protectedProp = 4;
1030
* @return {number} The number of ducks we've arranged in a row.
1032
AA_PublicClass.prototype.method = function() {
1033
// Legal accesses of these two properties.
1034
return this.privateProp_ + AA_PublicClass.staticPrivateProp_;
1041
* @extends {AA_PublicClass}
1043
AA_SubClass = function() {
1044
// Legal access of a protected static property.
1045
AA_PublicClass.staticProtectedProp = this.method();
1047
goog.inherits(AA_SubClass, AA_PublicClass);
1050
* @return {number} The number of ducks we've arranged in a row.
1052
AA_SubClass.prototype.method = function() {
1053
// Legal access of a protected instance property.
1054
return this.protectedProp;
1060
<STYLEPOINT title="JavaScript Types">
1061
<SUMMARY>Encouraged and enforced by the compiler.</SUMMARY>
1063
<p>When documenting a type in JSDoc, be as specific and accurate as
1064
possible. The types we support are
1065
<a href="http://wiki.ecmascript.org/doku.php?id=spec:spec">
1068
style types and JS1.x types.</p>
1069
<SUBSECTION title="The JavaScript Type Language">
1070
<p>The JS2 proposal contained a language for specifying JavaScript
1071
types. We use this language in JsDoc to express the types of
1072
function parameters and return values.</p>
1074
<p>As the JS2 proposal has evolved, this language has changed. The
1075
compiler still supports old syntaxes for types, but those syntaxes
1078
<table border="1" style="border-collapse:collapse" cellpadding="4">
1081
<th>Operator Name</th>
1083
<th>Description</th>
1084
<th>Deprecated Syntaxes</th>
1091
<code>{boolean}</code>, <code>{Window}</code>,
1092
<code>{goog.ui.Menu}</code>
1094
<td>Simply the name of a type.</td>
1099
<td>Type Application</td>
1101
<code>{Array.<string>}</code><br/>An array of strings.<p/>
1102
<code>{Object.<string, number>}</code>
1103
<br/>An object in which the keys are strings and the values
1106
<td>Patameterizes a type, by applying a set of type arguments
1107
to that type. The idea is analogous to generics in Java.
1115
<code>{(number|boolean)}</code><br/>A number or a boolean.
1117
<td>Indicates that a value might have type A OR type B.</td>
1119
<code>{(number,boolean)}</code>,
1120
<code>{number|boolean}</code>,
1121
<code>{(number||boolean)}</code>
1126
<td>Record Type</td>
1128
<code>{{myNum: number, myObject}}</code>
1129
<br/>An anonymous type with the given type members.
1132
<p>Indicates that the value has the specified members with the
1133
specified types. In this case, <code>myNum</code> with a
1134
type <code>number</code> and <code>myObject</code> with any
1136
<p>Notice that the braces are part of the type syntax. For
1137
example, to denote an <code>Array</code> of objects that
1138
have a <code>length</code> property, you might write
1139
<code>Array.<{length}></code>.</p>
1145
<td>Nullable type</td>
1147
<code>{?number}</code><br/> A number or NULL.
1149
<td>Indicates that a value is type A or <code>null</code>.
1150
By default, all object types are nullable.
1151
NOTE: Function types are not nullable.
1154
<code>{number?}</code>
1159
<td>Non-nullable type</td>
1161
<code>{!Object}</code><br/> An Object, but never the
1162
<code>null</code> value.
1164
<td>Indicates that a value is type A and not null. By default,
1165
all value types (boolean, number, string, and undefined) are
1169
<code>{Object!}</code>
1174
<td>Function Type</td>
1176
<code>{function(string, boolean)}</code><br/>
1177
A function that takes two arguments (a string and a boolean),
1178
and has an unknown return value.<br/>
1180
<td>Specifies a function.</td>
1185
<td>Function Return Type</td>
1187
<code>{function(): number}</code><br/>
1188
A function that takes no arguments and returns a number.<br/>
1190
<td>Specifies a function return type.</td>
1195
<td>Function <code>this</code> Type</td>
1197
<code>{function(this:goog.ui.Menu, string)}</code><br/>
1198
A function that takes one argument (a string), and executes
1199
in the context of a goog.ui.Menu.
1201
<td>Specifies the context type of a function type.</td>
1206
<td>Variable arguments</td>
1208
<code>{function(string, ...[number]): number}</code><br/>
1209
A function that takes one argument (a string), and then a
1210
variable number of arguments that must be numbers.
1212
<td>Specifies variable arguments to a function.</td>
1218
<a name="var-args-annotation"/>
1219
Variable arguments (in <code>@param</code> annotations)
1222
<code>@param {...number} var_args</code><br/>
1223
A variable number of arguments to an annotated function.
1226
Specifies that the annotated function accepts a variable
1227
number of arguments.
1233
<td>Function <a href="optional">optional arguments</a></td>
1235
<code>{function(?string=, number=)}</code><br/>
1236
A function that takes one optional, nullable string and one
1237
optional number as arguments. The <code>=</code> syntax is
1238
only for <code>function</code> type declarations.
1240
<td>Specifies optional arguments to a function.</td>
1246
<a name="optional-arg-annotation"/>
1247
Function <a href="optional">optional arguments</a>
1248
(in <code>@param</code> annotations)
1251
<code>@param {number=} opt_argument</code><br/>
1252
An optional parameter of type <code>number</code>.
1254
<td>Specifies that the annotated function accepts an optional
1260
<td>The ALL type</td>
1261
<td><code>{*}</code></td>
1262
<td>Indicates that the variable can take on any type.</td>
1268
<SUBSECTION title="Types in JavaScript">
1270
<table border="1" style="border-collapse:collapse" cellpadding="4">
1273
<th>Type Example</th>
1274
<th>Value Examples</th>
1275
<th>Description</th>
1302
<a href="#Wrapper_objects_for_primitive_types">
1331
<a href="#Wrapper_objects_for_primitive_types">
1359
<a href="#Wrapper_objects_for_primitive_types">
1371
</CODE_SNIPPET></td><td>
1381
</CODE_SNIPPET></td>
1422
<td>No return value</td>
1433
<td>Untyped Array</td>
1437
<td>Array.<number></td>
1449
<td>Array.<Array.<string>></td>
1452
[['one', 'two', 'three'], ['foo', 'bar']]
1455
<td>Array of Arrays of strings</td>
1463
{foo: 'abc', bar: 123, baz: null}
1470
<td>Object.<string></td>
1477
An Object in which the values are strings.
1482
<td>Object.<number, string></td>
1490
An Object in which the keys are numbers and the values
1491
are strings. <p/>Note that in JavaScript, the keys are always
1492
implicitly coverted to strings, so
1493
<code>obj['1'] == obj[1]</code>.
1494
So the key wil always be a string in for...in loops. But the
1495
compiler will verify the type if the key when indexing into
1510
<a href="#Wrapper_objects_for_primitive_types">
1517
<td>function(number, number): number</td>
1525
<td>function value</td>
1533
function SomeClass() {}
1542
<td>SomeInterface</td>
1546
function SomeInterface() {}
1548
SomeInterface.prototype.draw = function() {};
1555
<td>project.MyClass</td>
1559
project.MyClass = function () {}
1561
new project.MyClass()
1568
<td>project.MyEnum</td>
1571
/** @enum {string} */
1578
<td><a href="#enums">Enumeration</a></td>
1585
document.createElement('div')
1588
<td>Elements in the DOM.</td>
1595
document.body.firstChild
1598
<td>Nodes in the DOM.</td>
1602
<td>HTMLInputElement</td>
1605
htmlDocument.getElementsByTagName('input')[0]
1608
<td>A specific type of DOM element.</td>
1614
<SUBSECTION title="Nullable vs. Optional Parameters and Properties">
1615
<a name="optional"/>
1616
<p>Because JavaScript is a loosely-typed language, it is very
1617
important to understand the subtle differences between optional,
1618
nullable, and undefined function parameters and class
1621
<p>Object types (also known as reference types) are nullable by
1622
default. NOTE: Function types are not nullable by default. An
1623
object is defined as anything except a string, number, boolean,
1624
undefined, or null. For example, the following declaration</p>
1628
* Some class, initialized with a value.
1629
* @param {Object} value Some value.
1632
function MyClass(value) {
1638
this.myValue_ = value;
1642
<p>tells the compiler that the <code>myValue_</code> property holds
1643
either an Object or null. If <code>myValue_</code> must never be
1644
null, it should be declared like this:</p>
1648
* Some class, initialized with a non-null value.
1649
* @param {!Object} value Some value.
1652
function MyClass(value) {
1658
this.myValue_ = value;
1662
<p>This way, if the compiler can determine that somewhere in the code
1663
<code>MyClass</code> is initialized with a null value, it will issue
1668
<p>Optional parameters to functions may be undefined at runtime, so if
1669
they are assigned to class properties, those properties must be
1670
declared accordingly:</p>
1674
* Some class, initialized with an optional value.
1675
* @param {Object=} opt_value Some value (optional).
1678
function MyClass(opt_value) {
1681
* @type {Object|undefined}
1684
this.myValue_ = opt_value;
1688
<p>This tells the compiler that <code>myValue_</code> may hold an
1689
Object, null, or remain undefined.</p>
1691
<p>Note that the optional parameter <code>opt_value</code> is declared
1692
to be of type <code>{Object=}</code>, not
1693
<code>{Object|undefined}</code>. This is because optional
1694
parameters may, by definition, be undefined. While there is no harm
1695
in explicitly declaring an optional parameter as possibly undefined,
1696
it is both unnecessary and makes the code harder to read.</p>
1698
<p>Finally, note that being nullable and being optional are orthogonal
1699
properties. The following four declarations are all different:</p>
1703
* Takes four arguments, two of which are nullable, and two of which are
1705
* @param {!Object} nonNull Mandatory (must not be undefined), must not be null.
1706
* @param {Object} mayBeNull Mandatory (must not be undefined), may be null.
1707
* @param {!Object=} opt_nonNull Optional (may be undefined), but if present,
1709
* @param {Object=} opt_mayBeNull Optional (may be undefined), may be null.
1711
function strangeButTrue(nonNull, mayBeNull, opt_nonNull, opt_mayBeNull) {
1719
<STYLEPOINT title="Comments">
1720
<SUMMARY>Use JSDoc</SUMMARY>
1723
<a href="http://code.google.com/p/jsdoc-toolkit/">
1726
comments to document files, classes, methods and properties. Inline
1727
comments should be of the // variety. Additionally, we follow the
1728
<a href="cppguide.xml#Comments">
1729
C++ style for comments
1730
</a> in spirit. This means you should have:
1733
<li>copyright and authorship notice,</li>
1734
<li>a top-level (file-level) comment designed to orient readers
1735
unfamiliar with the code to what's in this file (e.g., a
1736
one-paragraph summary of what the major pieces are, how they fit
1737
together, and with what they interact),</li>
1738
<li>class, function, variable, and implementation comments as
1740
<li>an indication of the browsers in which the code is expected to
1741
work (if applicable), and</li>
1742
<li>proper capitalization, punctuation, and spelling.</li>
1745
<p>Avoid sentence fragments. Start sentences with a properly
1746
capitalized word, and end them with punctuation.</p>
1748
<p>Pretend there's some novice programmer that's going to come along and
1749
have to maintain the code after you. There very well just might
1752
<p>There are now many compiler passes that extract type information from
1753
JSDoc, in order to provide better code validation, removal, and
1754
compression. It is, therefore, very important that you use full and
1757
<SUBSECTION title="Top/File-Level Comments">
1760
The top level comment is designed
1761
to orient readers unfamiliar with the code to what is in this file.
1762
It should provide a description of the file's contents, its
1763
author(s), and any dependencies or compatibility information. As an
1767
// Copyright 2009 Google Inc. All Rights Reserved.
1770
* @fileoverview Description of file, its uses and information
1771
* about its dependencies.
1772
* @author user@google.com (Firstname Lastname)
1779
<SUBSECTION title="Class Comments">
1780
<p>Classes must be documented with a description and usage.
1781
The constructor parameters must also be documented.
1782
If the class inherits from another class,
1783
that should be documented with an <code>@extends</code> tag.
1784
If the class implements an interface,
1785
that should be documented with an <code>@implements</code> tag.
1790
* Class making something fun and easy.
1791
* @param {string} arg1 An argument that makes this more interesting.
1792
* @param {Array.<number>} arg2 List of numbers to be processed.
1794
* @extends {goog.Disposable}
1796
project.MyClass = function(arg1, arg2) {
1799
goog.inherits(project.MyClass, goog.Disposable);
1803
<SUBSECTION title="Method and Function Comments">
1804
<p>A description must be provided along with parameters. Use full
1805
sentences. Method descriptions should start with a sentence written
1806
in the third person declarative voice.</p>
1810
* Converts text to some completely different text.
1811
* @param {string} arg1 An argument that makes this more interesting.
1812
* @return {string} Some return value.
1814
project.MyClass.prototype.someMethod = function(arg1) {
1819
* Operates on an instance of MyClass and returns something.
1820
* @param {project.MyClass} obj Instance of MyClass which leads to a long
1821
* comment that needs to be wrapped to two lines.
1822
* @return {boolean} Whether something occured.
1824
function PR_someMethod(obj) {
1829
<p>For simple getters that take no parameters, the description can be
1834
* @return {Element} The element for the component.
1836
goog.ui.Component.prototype.getElement = function() {
1837
return this.element_;
1842
<SUBSECTION title="Property Comments">
1843
<p>It is also nice to have comments for properties.</p>
1847
* Maximum number of things per pane.
1850
project.MyClass.prototype.someProperty = 4;
1854
<SUBSECTION title="Type Cast Comments">
1855
<p>In cases where type-checking doesn't accurately infer the type of
1856
an expression, it is possible to add a type cast comment by adding a
1857
type annotation comment and enclosing the expression in
1858
parenthesis. The parentheses are required, and may surround the type
1859
annotation comment as well.</p>
1862
/** @type {number} */ (x)
1863
(/** @type {number} */ x)
1867
<SUBSECTION title="JSDoc Indentation">
1868
<p>If you have to line break a <code>@param</code>,
1869
<code>@return</code>, <code>@supported</code>, <code>@this</code> or
1870
<code>@deprecated</code> you should treat this as breaking a code
1871
statement and indent it four spaces.</p>
1875
* Illustrates line wrapping for long param/return descriptions.
1876
* @param {string} foo This is a param with a description too long to fit in
1878
* @return {number} This returns something that has a description too long to
1881
project.MyClass.prototype.method = function(foo) {
1886
<p>You should not indent the <code>@fileoverview</code> command.</p>
1888
<p>Even though it is not preferred, it is also acceptable to line up
1889
the description. This has the side effect that you will have to
1890
realign the text every time you change a variable name so this will
1891
soon get your code out of sync.</p>
1895
* This is NOT the preferred indentation method.
1896
* @param {string} foo This is a param with a description too long to fit in
1898
* @return {number} This returns something that has a description too long to
1901
project.MyClass.prototype.method = function(foo) {
1907
<SUBSECTION title="Enums">
1911
* Enum for tri-state values.
1914
project.TriState = {
1921
<p>Note that enums are also valid <a href="#JavaScript_Types">types</a>
1922
and thus can be used as parameter types, etc.</p>
1926
* Sets project state.
1927
* @param {project.TriState} state New project state.
1929
project.setState = function(state) {
1935
<SUBSECTION title="Typedefs">
1936
<p>Sometimes types can get complicated. A function that accepts
1937
content for an Element might look like:</p>
1941
* @param {string} tagName
1942
* @param {(string|Element|Text|Array.<Element>|Array.<Text>)} contents
1945
goog.createElement = function(tagName, contents) {
1950
<p>You can define commonly used type expressions with a
1951
<code>@typedef</code> tag. For example,</p>
1954
/** @typedef {(string|Element|Text|Array.<Element>|Array.<Text>)} */
1955
goog.ElementContent;
1958
* @param {string} tagName
1959
* @param {goog.ElementContent} contents
1962
goog.createElement = function(tagName, contents) {
1968
<SUBSECTION title="JSDoc Tag Reference">
1969
<table border="1" style="border-collapse:collapse" cellpadding="4">
1973
<th>Template & Examples</th>
1974
<th>Description</th>
1975
<th>Type-Checking Support</th>
1980
<td><a name="tag-param">@param</a></td>
1982
<tt>@param {Type} varname Description</tt>
1983
<p><i>For example:</i></p>
1986
* Queries a Baz for items.
1987
* @param {number} groupNum Subgroup id to query.
1988
* @param {string|number|null} term An itemName,
1989
* or itemId, or null to search everything.
1991
goog.Baz.prototype.query = function(groupNum, term) {
1997
Used with method, function and constructor calls to document
1998
the arguments of a function.
2000
<td>Fully supported.</td>
2004
<td><a name="tag-return">@return</a></td>
2006
<tt>@return {Type} Description</tt>
2007
<p><i>For example:</i></p>
2010
* @return {string} The hex ID of the last item.
2012
goog.Baz.prototype.getLastId = function() {
2019
Used with method and function calls to document the return
2020
type. When writing descriptions for boolean parameters,
2021
prefer "Whether the component is visible" to "True if the
2022
component is visible, false otherwise". If there is no return
2023
value, do not use an <code>@return</code> tag.
2025
<td>Fully supported.</td>
2030
<a name="tag-author">@author</a>
2034
<tt>@author username@google.com (first last)</tt>
2035
<p><i>For example:</i></p>
2038
* @fileoverview Utilities for handling textareas.
2039
* @author kuth@google.com (Uthur Pendragon)
2044
Document the author of a file or the owner of a test,
2045
generally only used in the <code>@fileoverview</code> comment.
2048
<td>Unrelated to type checking.</td>
2052
<td><a name="tag-see">@see</a></td>
2055
<p><i>For example:</i></p>
2058
* Adds a single item, recklessly.
2061
* @see goog.RecklessAdder#add
2065
<td>Reference a lookup to another class function or method.</td>
2066
<td>Unrelated to type checking.</td>
2070
<td><a name="tag-fileoverview">@fileoverview</a></td>
2072
<tt>@fileoverview Description</tt>
2073
<p><i>For example:</i></p>
2076
* @fileoverview Utilities for doing things that require this very long
2077
* but not indented comment.
2078
* @author kuth@google.com (Uthur Pendragon)
2082
<td>Makes the comment block provide file level information.</td>
2083
<td>Unrelated to type checking.</td>
2087
<td><a name="tag-constructor">@constructor</a></td>
2089
<tt>@constructor</tt>
2090
<p><i>For example:</i></p>
2096
function GM_Rect() {
2102
Used in a class's documentation to indicate the constructor.
2105
Yes. If omitted the compiler will prohibit instantiation.
2110
<td><a name="tag-interface">@interface</a></td>
2113
<p><i>For example:</i></p>
2119
function Shape() {};
2120
Shape.prototype.draw = function() {};
2127
function Polygon() {};
2128
Polygon.prototype.getSides = function() {};
2131
<td>Used to indicate that the function defines an inteface.</td>
2133
Yes. The compiler will warn about instantiating an interface.
2138
<td><a name="tag-type">@type</a></td>
2144
<p><i>For example:</i></p>
2147
* The message hex ID.
2154
Identifies the type of a variable, property, or expression.
2155
Curly braces are not required around most types, but some
2156
projects mandate them for all types, for consistency.
2162
<td><a name="tag-extends">@extends</a></td>
2168
<p><i>For example:</i></p>
2171
* Immutable empty node list.
2173
* @extends goog.ds.BasicNodeList
2175
goog.ds.EmptyNodeList = function() {
2181
Used with @constructor to indicate that a class inherits from
2182
another class. Curly braces around the type are optional.
2188
<td><a name="tag-implements">@implements</a></td>
2191
@implements Type<br/>
2194
<p><i>For example:</i></p>
2200
function Shape() {};
2201
Shape.prototype.draw = function() {};
2205
* @implements {Shape}
2207
function Square() {};
2208
Square.prototype.draw = function() {
2214
Used with @constructor to indicate that a class implements an
2215
interface. Curly braces around the type are optional.
2218
Yes. The compiler will warn about incomplete implementations
2224
<td><a name="tag-private">@private</a></td>
2227
<p><i>For example:</i></p>
2230
* Handlers that are listening to this logger.
2231
* @type Array.<Function>
2234
this.handlers_ = [];
2238
Used in conjunction with a trailing underscore on the method
2239
or property name to indicate that the member is
2240
<a href="#Visibility__private_and_protected_fields_">private</a>.
2241
Trailing underscores may eventually be deprecated as tools are
2242
updated to enforce <tt>@private</tt>.
2244
<td>Enforced with a flag.</td>
2248
<td><a name="tag-protected">@protected</a></td>
2251
<p><i>For example:</i></p>
2254
* Sets the component's root element to the given element. Considered
2255
* protected and final.
2256
* @param {Element} element Root element for the component.
2259
goog.ui.Component.prototype.setElementInternal = function(element) {
2265
Used to indicate that the member or property is
2266
<a href="#Visibility__private_and_protected_fields_">protected</a>.
2267
Should be used in conjunction with names with no trailing
2270
<td>Enforced with a flag.</td>
2274
<td><a name="tag-this">@this</a></td>
2280
<p><i>For example:</i></p>
2282
pinto.chat.RosterWidget.extern('getRosterElement',
2284
* Returns the roster widget element.
2285
* @this pinto.chat.RosterWidget
2289
return this.getWrappedComponent_().getElement();
2294
The type of the object in whose context a particular method is
2295
called. Required when the <tt>this</tt> keyword is referenced
2296
from a function that is not a prototype method.
2302
<td><a name="tag-supported">@supported</a></td>
2304
<tt>@supported Description</tt>
2305
<p><i>For example:</i></p>
2308
* @fileoverview Event Manager
2309
* Provides an abstracted interface to the
2310
* browsers' event systems.
2311
* @supported So far tested in IE6 and FF1.5
2316
Used in a fileoverview to indicate what browsers are supported
2319
<td>Unrelated to type checking.</td></tr>
2322
<td><a name="tag-enum">@enum</a></td>
2324
<tt>@enum {Type}</tt>
2325
<p><i>For example:</i></p>
2328
* Enum for tri-state values.
2331
project.TriState = {
2338
<td>Used for documenting enum types.</td>
2339
<td>Fully supported. If Type is omitted, number assumed.</td>
2343
<td><a name="tag-deprecated">@deprecated</a></td>
2345
<tt>@deprecated Description</tt>
2346
<p><i>For example:</i></p>
2349
* Determines whether a node is a field.
2350
* @return {boolean} True if the contents of
2351
* the element are editable, but the element
2353
* @deprecated Use isField().
2355
BN_EditUtil.isTopEditableField = function(node) {
2361
Used to tell that a function, method or property should not be
2362
used any more. Always provide instructions on what callers
2365
<td>Unrelated to type checking</td>
2369
<td><a name="tag-override">@override</a></td>
2372
<p><i>For example:</i></p>
2375
* @return {string} Human-readable representation of project.SubClass.
2378
project.SubClass.prototype.toString() {
2384
Indicates that a method or property of a subclass
2385
intentionally hides a method or property of the superclass. If
2386
no other documentation is included, the method or property
2387
also inherits documentation from its superclass.
2393
<td><a name="tag-inheritDoc">@inheritDoc</a></td>
2395
<tt>@inheritDoc</tt>
2396
<p><i>For example:</i></p>
2399
project.SubClass.prototype.toString() {
2405
Indicates that a method or property of a subclass
2406
intentionally hides a method or property of the superclass,
2407
and has exactly the same documentation. Notice that
2408
@inheritDoc implies @override.
2414
<td><a name="tag-code">@code</a></td>
2416
<tt>{@code ...}</tt>
2417
<p><i>For example:</i></p>
2420
* Moves to the next position in the selection.
2421
* Throws {@code goog.iter.StopIteration} when it
2422
* passes the end of the range.
2423
* @return {Node} The node at the next position.
2425
goog.dom.RangeIterator.prototype.next = function() {
2431
Indicates that a term in a JSDoc description is code so it may
2432
be correctly formatted in generated documentation.
2434
<td>Not applicable.</td>
2438
<td><a name="tag-license">@license</a> or
2439
<a name="tag-preserve">@preserve</a></td>
2441
<tt>@license Description</tt>
2442
<p><i>For example:</i></p>
2445
* @preserve Copyright 2009 SomeThirdParty.
2446
* Here is the full license text and copyright
2447
* notice for this file. Note that the notice can span several
2448
* lines and is only terminated by the closing star and slash:
2453
Anything marked by @license or @preserve will be retained by
2454
the compiler and output at the top of the compiled code for
2455
that file. This annotation allows important notices (such as
2456
legal licenses or copyright text) to survive compilation
2457
unchanged. Line breaks are preserved.
2459
<td>Unrelated to type checking.</td>
2463
<td><a name="tag-noalias">@noalias</a></td>
2466
<p><i>For example:</i></p>
2473
Used in an externs file to indicate to the compiler that the
2474
variable or function should not be aliased as part of the
2475
alias externals pass of the compiler.
2477
<td>Unrelated to type checking.</td>
2481
<td><a name="tag-define">@define</a></td>
2483
<tt>@define {Type} description</tt>
2484
<p><i>For example:</i></p>
2486
/** @define {boolean} */
2487
var TR_FLAGS_ENABLE_DEBUG = true;
2489
/** @define {boolean} */
2490
goog.userAgent.ASSUME_IE = false;
2494
Indicates a constant that can be overridden by the compiler at
2495
compile-time. In the example, the compiler flag
2496
<tt>--define='goog.userAgent.ASSUME_IE=true'</tt>
2497
could be specified in the BUILD file to indicate that the
2498
constant <tt>goog.userAgent.ASSUME_IE</tt> should be replaced
2501
<td>Unrelated to type checking.</td>
2507
<td><a name="tag-export">@export</a></td>
2510
<p><i>For example:</i></p>
2513
foo.MyPublicClass.prototype.myPublicMethod = function() {
2519
<p>Given the code on the left, when the compiler is run with
2520
the <tt>--generate_exports</tt> flag, it will generate the
2523
goog.exportSymbol('foo.MyPublicClass.prototype.myPublicMethod',
2524
foo.MyPublicClass.prototype.myPublicMethod);
2526
<p>which will export the symbols to uncompiled code.
2527
Code that uses the <tt>@export</tt> annotation must either</p>
2529
<li>include <tt>//javascript/closure/base.js</tt>, or</li>
2530
<li>define both <tt>goog.exportSymbol</tt> and
2531
<tt>goog.exportProperty</tt> with the same method
2532
signature in their own codebase.</li>
2535
<td>Unrelated to type checking.</td>
2539
<td><a name="tag-const">@const</a></td>
2542
<p><i>For example:</i></p>
2544
/** @const */ var MY_BEER = 'stout';
2547
* My namespace's favorite kind of beer.
2551
mynamespace.MY_BEER = 'stout';
2553
/** @const */ MyClass.MY_BEER = 'stout';
2557
<p>Marks a variable as read-only and suitable for inlining.
2558
Generates warnings if it is rewritten.</p>
2559
<p>Constants should also be ALL_CAPS, but the annotation
2560
should help eliminate reliance on the naming convention.
2561
Although @final is listed at jsdoc.org and is supported as
2562
equivalent to @const in the compiler, it is discouraged.
2563
@const is consistent with JS1.5's const keyword. Note that
2564
changes to properties of const objects are not currently
2565
prohibited by the compiler (inconsistent with C++ const
2566
semantics). The type declaration can be omitted if it can be
2567
clearly inferred. If present, it must be on its own line. An
2568
additional comment about the variable is optional.</p>
2570
<td>Supported by type checking.</td>
2574
<td><a name="tag-nosideeffects">@nosideeffects</a></td>
2576
<tt>@nosideeffects</tt>
2577
<p><i>For example:</i></p>
2579
/** @nosideeffects */
2580
function noSideEffectsFn1() {
2584
/** @nosideeffects */
2585
var noSideEffectsFn2 = function() {
2589
/** @nosideeffects */
2590
a.prototype.noSideEffectsFn3 = function() {
2596
This annotation can be used as part of function and
2597
constructor declarations to indicate that calls to the
2598
declared function have no side-effects. This annotation
2599
allows the compiler to remove calls to these functions if the
2600
return value is not used.
2602
<td>Unrelated to type checking.</td>
2606
<td><a name="tag-typedef">@typedef</a></td>
2609
<p><i>For example:</i></p>
2611
/** @typedef {(string|number)} */
2614
/** @param {goog.NumberLike} x A number or a string. */
2615
goog.readNumber = function(x) {
2621
This annotation can be used to declare an alias of a more
2628
<td><a name="tag-externs">@externs</a></td>
2631
<p><i>For example:</i></p>
2634
* @fileoverview This is an externs file.
2656
You may also see other types of JSDoc annotations in third-party
2657
code. These annotations appear in the
2658
<a href="http://code.google.com/p/jsdoc-toolkit/wiki/TagReference">
2659
JSDoc Toolkit Tag Reference
2661
but are currently discouraged in Google code. You should consider
2662
them "reserved" names for future use. These include:
2669
<li>@constructs</li>
2693
<SUBSECTION title="HTML in JSDoc">
2694
<p>Like JavaDoc, JSDoc supports many HTML tags, like <code>,
2695
<pre>, <tt>, <strong>, <ul>, <ol>,
2696
<li>, <a>, and others.</p>
2698
<p>This means that plaintext formatting is not respected. So, don't
2699
rely on whitespace to format JSDoc:</p>
2703
* Computes weight based on three factors:
2710
<p>It'll come out like this:</p>
2712
<tt>Computes weight based on three factors: items sent items received items received</tt>
2714
<p>Instead, do this:</p>
2718
* Computes weight based on three factors:
2720
* <li>items sent
2721
* <li>items received
2722
* <li>last timestamp
2727
<p>Also, don't include HTML or HTML-like tags unless you want them to
2728
be interpreted as HTML.</p>
2732
* Changes <b> tags to <span> tags.
2736
<p>It'll come out like this:</p>
2738
<tt>Changes <b> tags to <span> tags.</span></b></tt>
2740
<p>On the other hand, people need to be able to read this in its
2741
plaintext form too, so don't go overboard with the HTML:</p>
2745
* Changes &lt;b&gt; tags to &lt;span&gt; tags.
2749
<p>People will know what you're talking about if you leave the
2750
angle-brackets out, so do this:</p>
2754
* Changes 'b' tags to 'span' tags.
2761
<STYLEPOINT title="Compiling">
2762
<SUMMARY>Encouraged</SUMMARY>
2766
<p>Use of JS compilers such as the
2767
<a href="http://code.google.com/closure/compiler/">Closure Compiler</a>
2776
<STYLEPOINT title="Tips and Tricks">
2777
<SUMMARY>JavaScript tidbits</SUMMARY>
2779
<SUBSECTION title="True and False Boolean Expressions">
2780
<p>The following are all false in boolean expressions:</p>
2782
<li><code>null</code></li>
2783
<li><code>undefined</code></li>
2784
<li><code>''</code> the empty string</li>
2785
<li><code>0</code> the number</li>
2787
<p>But be careful, because these are all true:</p>
2789
<li><code>'0'</code> the string</li>
2790
<li><code>[]</code> the empty array</li>
2791
<li><code>{}</code> the empty object</li>
2794
<p>This means that instead of this:</p>
2798
<p>you can write this shorter code (as long as you don't expect x to
2799
be 0, or the empty string, or false):</p>
2804
<p>And if you want to check a string to see if it is null or empty,
2805
you could do this:</p>
2807
if (y != null && y != '') {
2809
<p>But this is shorter and nicer:</p>
2814
<p><strong>Caution:</strong> There are many unintuitive things about
2815
boolean expressions. Here are some of them:</p>
2818
Boolean('0') == true<br/>
2819
'0' != true</code></li>
2823
0 == false</code></li>
2825
Boolean(null) == false<br/>
2827
null != false</code></li>
2829
Boolean(undefined) == false<br/>
2830
undefined != true<br/>
2831
undefined != false</code></li>
2833
Boolean([]) == true<br/>
2835
[] == false</code></li>
2837
Boolean({}) == true<br/>
2839
{} != false</code></li>
2843
<SUBSECTION title="Conditional (Ternary) Operator (?:)">
2844
<p>Instead of this:</p>
2852
<p>you can write this:</p>
2854
return val ? foo() : bar();
2857
<p>The ternary conditional is also useful when generating HTML:</p>
2859
var html = '<input type="checkbox"' +
2860
(isChecked ? ' checked' : '') +
2861
(isEnabled ? '' : ' disabled') +
2866
<SUBSECTION title="&& and ||">
2867
<p>These binary boolean operators are short-circuited, and evaluate
2868
to the last evaluated term.</p>
2870
<p>"||" has been called the 'default' operator, because instead of
2873
/** @param {*=} opt_win */
2874
function foo(opt_win) {
2884
<p>you can write this:</p>
2886
/** @param {*=} opt_win */
2887
function foo(opt_win) {
2888
var win = opt_win || window;
2893
<p>"&&" is also useful for shortening code. For instance,
2894
instead of this:</p>
2898
if (node.kids[index]) {
2899
foo(node.kids[index]);
2905
<p>you could do this:</p>
2907
if (node && node.kids && node.kids[index]) {
2908
foo(node.kids[index]);
2914
var kid = node && node.kids && node.kids[index];
2920
<p>However, this is going a little too far:</p>
2922
node && node.kids && node.kids[index] && foo(node.kids[index]);
2926
<SUBSECTION title="Use join() to Build Strings">
2927
<p>It is common to see this:</p>
2929
function listHtml(items) {
2930
var html = '<div class="foo">';
2931
for (var i = 0; i < items.length; ++i) {
2935
html += itemHtml(items[i]);
2937
html += '</div>';
2942
<p>but this is slow in Internet Explorer, so it is better to do
2945
function listHtml(items) {
2947
for (var i = 0; i < items.length; ++i) {
2948
html[i] = itemHtml(items[i]);
2950
return '<div class="foo">' + html.join(', ') + '</div>';
2954
<p>You can also use an array as a stringbuilder, and convert it into
2955
a string with <code>myArray.join('')</code>. Note that since
2956
assigning values to an array is faster than using
2957
<code>push()</code> you should use assignment where possible.</p>
2960
<SUBSECTION title="Iterating over Node Lists">
2961
<p>Node lists are often implemented as node iterators with a filter.
2962
This means that getting a property like length is O(n), and
2963
iterating over the list by re-checking the length will be
2966
var paragraphs = document.getElementsByTagName('p');
2967
for (var i = 0; i < paragraphs.length; i++) {
2968
doSomething(paragraphs[i]);
2972
<p>It is better to do this instead:</p>
2974
var paragraphs = document.getElementsByTagName('p');
2975
for (var i = 0, paragraph; paragraph = paragraphs[i]; i++) {
2976
doSomething(paragraph);
2980
<p>This works well for all collections and arrays as long as the array
2981
does not contain things that are treated as boolean false.</p>
2983
<p>In cases where you are iterating over the childNodes you can also
2984
use the firstChild and nextSibling properties.</p>
2986
var parentNode = document.getElementById('foo');
2987
for (var child = parentNode.firstChild; child; child = child.nextSibling) {
3000
<em>BE CONSISTENT</em>.
3004
If you're editing code, take a few minutes to look at the code
3005
around you and determine its style. If they use spaces around
3006
all their arithmetic operators, you should too. If their
3007
comments have little boxes of hash marks around them, make your
3008
comments have little boxes of hash marks around them too.
3012
The point of having style guidelines is to have a common vocabulary
3013
of coding so people can concentrate on what you're saying rather
3014
than on how you're saying it. We present global style rules here so
3015
people know the vocabulary, but local style is also important. If
3016
code you add to a file looks drastically different from the existing
3017
code around it, it throws readers out of their rhythm when they go to
3018
read it. Avoid this.
3033
Fritz Schneider<br/>