Skip to content

Instantly share code, notes, and snippets.

@teppeis
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teppeis/b647ce9aaba9ebd7ee66 to your computer and use it in GitHub Desktop.
Save teppeis/b647ce9aaba9ebd7ee66 to your computer and use it in GitHub Desktop.
Google JavaScript Style GuideのRev. 2.11:2.93 (svn r65:r112) のdiff http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml
Index: javascriptguide.xml
===================================================================
--- javascriptguide.xml (リビジョン 65)
+++ javascriptguide.xml (リビジョン 138)
@@ -3,14 +3,14 @@
<GUIDE title="Google JavaScript Style Guide">
<p class="revision">
- Revision 2.11
+ Revision 2.93
</p>
<address>
Aaron Whyte<br/>
Bob Jervis<br/>
Dan Pupius<br/>
- Eric Arvidsson<br/>
+ Erik Arvidsson<br/>
Fritz Schneider<br/>
Robby Walker<br/>
</address>
@@ -44,11 +44,15 @@
+
+
</CATEGORY>
</OVERVIEW>
<CATEGORY title="JavaScript Language Rules">
+
+
<STYLEPOINT title="var">
<SUMMARY>
Declarations with <code>var</code>: Always
@@ -67,37 +71,105 @@
<STYLEPOINT title="Constants">
<SUMMARY>
- &gt;Use <code>NAMES_LIKE_THIS</code> for constants.
- Use <code>@const</code> where appropriate.
- Never use the <code>const</code> keyword.
+ <ul>
+ <li>Use <code>NAMES_LIKE_THIS</code> for constant <em>values</em>.</li>
+ <li>Use <code>@const</code> to indicate a constant (non-overwritable)
+ <em>pointer</em> (a variable or property).</li>
+ <li>Never use the
+ <a href="https://developer.mozilla.org/en/JavaScript/Reference/Statements/const">
+ <code>const</code> keyword</a>
+ as it's not supported in Internet Explorer.</li>
+ </ul>
</SUMMARY>
<BODY>
<DECISION>
- <p>For simple primitive value constants, the naming convention is
- enough.</p>
- <CODE_SNIPPET>
- /**
- * The number of seconds in a minute.
- * @type {number}
- */
- goog.example.SECONDS_IN_A_MINUTE = 60;
- </CODE_SNIPPET>
- <p>For non-primitives, use the <code>@const</code> annotation.</p>
- <CODE_SNIPPET>
- /**
- * The number of seconds in each of the given units.
- * @type {Object.&lt;number&gt;}
- * @const
- */
- goog.example.SECONDS_TABLE = {
- minute: 60,
- hour: 60 * 60
- day: 60 * 60 * 24
- }
- </CODE_SNIPPET>
- <p>This allows the compiler to enforce constant-ness.</p>
- <p>As for the <code>const</code> keyword, Internet Explorer doesn't
- parse it, so don't use it.</p>
+ <SUBSECTION title="Constant values">
+
+ <p>If a value is intended to be <em>constant</em>
+ and <em>immutable</em>, it should be given a name
+ in <code>CONSTANT_VALUE_CASE</code>.
+ <code>ALL_CAPS</code> additionally implies <code>@const</code>
+ (that the value is not overwritable).
+ </p>
+
+ <p>Primitive types (<code>number</code>, <code>string</code>,
+ <code>boolean</code>) are constant values.</p>
+
+ <p><code>Objects</code>'
+ immutability is more subjective — objects should be
+ considered immutable only if they do not demonstrate observable
+ state change. This is not enforced by the compiler.</p>
+
+
+ </SUBSECTION>
+
+ <SUBSECTION title="Constant pointers (variables and properties)">
+ <p>The <code>@const</code> annotation on a variable or property
+ implies that it is not overwritable. This is enforced by the
+ compiler at build time. This behavior is consistent with the
+ <a href="https://developer.mozilla.org/en/JavaScript/Reference/Statements/const">
+ <code>const</code> keyword</a> (which we do not use due to the
+ lack of support in Internet Explorer).</p>
+
+ <p>A <code>@const</code> annotation on a method additionally
+ implies that the method cannot not be overridden in subclasses.
+ </p>
+
+ <p>A <code>@const</code> annotation on a constructor implies the
+ class cannot be subclassed (akin to <code>final</code> in Java).
+ </p>
+
+ </SUBSECTION>
+
+ <SUBSECTION title="Examples">
+
+ <p>Note that <code>@const</code> does not necessarily imply
+ <code>CONSTANT_VALUES_CASE</code>.
+
+ However, <code>CONSTANT_VALUES_CASE</code>
+ <em>does</em> imply <code>@const</code>.
+ </p>
+
+ <CODE_SNIPPET>
+ /**
+ * Request timeout in milliseconds.
+ * @type {number}
+ */
+ goog.example.TIMEOUT_IN_MILLISECONDS = 60;
+ </CODE_SNIPPET>
+
+ <p>The number of seconds in a minute never changes. It is a
+ constant value. <code>ALL_CAPS</code>
+ also implies <code>@const</code>, so the constant cannot be
+ overwritten.
+ </p>
+
+ <p>The open source compiler will allow the symbol to be
+ overwritten because the constant is
+ <em>not</em> marked as <code>@const</code>.</p>
+
+ <CODE_SNIPPET>
+ /**
+ * Map of URL to response string.
+ * @const
+ */
+ MyClass.fetchedUrlCache_ = new goog.structs.Map();
+ </CODE_SNIPPET>
+
+ <CODE_SNIPPET>
+ /**
+ * Class that cannot be subclassed.
+ * @const
+ * @constructor
+ */
+ sloth.MyFinalClass = function() {};
+ </CODE_SNIPPET>
+
+ <p>In this case, the pointer can never be overwritten, but
+ value is highly mutable and <b>not</b> constant (and thus in
+ <code>camelCase</code>, not <code>ALL_CAPS</code>).</p>
+ </SUBSECTION>
+
</DECISION>
</BODY>
</STYLEPOINT>
@@ -129,7 +201,7 @@
// 2. Trying to do one thing on Internet Explorer and another on Firefox.
// I know you'd never write code like this, but throw me a bone.
- [normalVersion, ffVersion][isIE]();
+ [ffVersion, ieVersion][isIE]();
var THINGS_TO_EAT = [apples, oysters, sprayOnCheese] // No semicolon here.
@@ -144,23 +216,38 @@
"called" resulting in an error.</li>
<li>You will most likely get a 'no such property in undefined'
error at runtime as it tries to call
- <code>x[ffVersion][isIE]()</code>.</li>
- <li><code>die</code> is called unless
- <code>resultOfOperation()</code> is <code>NaN</code> and
- <code>THINGS_TO_EAT</code> gets assigned the result of
- <code>die()</code>.</li>
+ <code>x[ffVersion, ieVersion][isIE]()</code>.</li>
+ <li><code>die</code> is always called since the array minus 1 is
+ <code>NaN</code> which is never equal to anything (not even if
+ <code>resultOfOperation()</code> returns <code>NaN</code>) and
+ <code>THINGS_TO_EAT</code> gets assigned the result of
+ <code>die()</code>.</li>
</ol>
</SUBSECTION>
<SUBSECTION title="Why?">
- <p>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
- signal the end of the statement. Javascript never ends a statement
- if the next token is an infix or bracket operator.</p>
+ <p>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 signal
+ the end of the statement. Javascript never ends a statement if the
+ next token is an infix or bracket operator.</p>
<p>This has really surprised people, so make sure your assignments end
with semicolons.</p>
</SUBSECTION>
+ <SUBSECTION title="Clarification: Semicolons and functions">
+ <p>Semicolons should be included at the end of function expressions,
+ but not at the end of function declarations. The distinction is
+ best illustrated with an example:</p>
+ <CODE_SNIPPET>
+ var foo = function() {
+ return true;
+ }; // semicolon here.
+
+ function foo() {
+ return true;
+ } // no semicolon here.
+ </CODE_SNIPPET>
+ </SUBSECTION>
</BODY>
</STYLEPOINT>
@@ -193,7 +280,7 @@
Expression to define a function within a block:</p>
<CODE_SNIPPET>
if (x) {
- var foo = function() {}
+ var foo = function() {};
}
</CODE_SNIPPET>
</BODY>
@@ -271,8 +358,7 @@
<a href="http://code.google.com/closure/library/">
the Closure Library
</a>
- or something similar.
-
+ or a similar library function.
</p>
<CODE_SNIPPET>
function D() {
@@ -287,27 +373,68 @@
</BODY>
</STYLEPOINT>
- <STYLEPOINT title="Method definitions">
- <SUMMARY><code>Foo.prototype.bar = function() { ... };</code></SUMMARY>
+ <STYLEPOINT title="Method and property definitions">
+ <SUMMARY><code>/** @constructor */
+ function SomeConstructor() {
+ this.someProperty = 1;
+ }
+ Foo.prototype.someMethod = function() { ... };</code></SUMMARY>
<BODY>
- <p>While there are several methods for attaching methods and
- properties to a constructor, the preferred style is:</p>
+ <p>While there are several ways to attach methods and properties to an
+ object created via "new", the preferred style for methods
+ is:</p>
<CODE_SNIPPET>
Foo.prototype.bar = function() {
/* ... */
};
</CODE_SNIPPET>
+ <p>The preferred style for other properties is to initialize the field
+ in the constructor:</p>
+ <CODE_SNIPPET>
+ /** @constructor */
+ function Foo() {
+ this.bar = value;
+ }
+ </CODE_SNIPPET>
+ <SUBSECTION title="Why?">
+ <p>Current JavaScript engines optimize based on the "shape"
+ of an object, <a href="https://developers.google.com/v8/design#prop_access">
+ adding a property to an object (including overriding
+ a value set on the prototype) changes the shape and can degrade
+ performance.</a></p>
+ </SUBSECTION>
</BODY>
</STYLEPOINT>
+ <STYLEPOINT title="delete">
+ <SUMMARY>Prefer <code>this.foo = null</code>.</SUMMARY>
+ <BODY>
+ <CODE_SNIPPET>
+ Foo.prototype.dispose = function() {
+ this.property_ = null;
+ };
+ </CODE_SNIPPET>
+ <p>Instead of:</p>
+ <BAD_CODE_SNIPPET>
+ Foo.prototype.dispose = function() {
+ delete this.property_;
+ };
+ </BAD_CODE_SNIPPET>
+ <p>In modern JavaScript engines, changing the number of properties on an
+ object is much slower than reassigning the values. The delete keyword
+ should be avoided except when it is necessary to remove a property
+ from an object's iterated list of keys, or to change the result of
+ <code>if (key in obj)</code>.</p>
+ </BODY>
+ </STYLEPOINT>
+
<STYLEPOINT title="Closures">
<SUMMARY>Yes, but be careful.</SUMMARY>
<BODY>
<p>The ability to create closures is perhaps the most useful and often
overlooked feature of JS. Here is
<a href="http://jibbering.com/faq/faq_notes/closures.html">
- a good description of how closures work
- </a>.</p>
+ a good description of how closures work</a>.</p>
<p>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
@@ -329,7 +456,7 @@
}
function bar(a, b) {
- return function() { /* uses a and b */ }
+ return function() { /* uses a and b */ };
}
</CODE_SNIPPET>
</BODY>
@@ -337,53 +464,43 @@
<STYLEPOINT title="eval()">
<SUMMARY>
- Only for deserialization (e.g. evaluating RPC responses)
+ Only for code loaders and REPL (Read–eval–print loop)
</SUMMARY>
<BODY>
<p><code>eval()</code> makes for confusing semantics and is dangerous
to use if the string being <code>eval()</code>'d contains user input.
- There's usually a better, more clear, safer way to write your code, so
- its used is generally not permitted. However <code>eval</code> makes
- deserialization considerably easier than the non-<code>eval</code>
- alternatives, so its use is acceptable for this task (for example, to
- evaluate RPC responses).</p>
- <p>Deserialization is the process of transforming a series of bytes into
- an in-memory data structure. For example, you might write objects out
- to a file as:</p>
+ There's usually a better, clearer, and safer way to write your code,
+ so its use is generally not permitted.</p>
+
+ <p>For RPC you can always use JSON and read the result using
+ <code>JSON.parse()</code> instead of <code>eval()</code>.</p>
+
+ <p>Let's assume we have a server that returns something like this:</p>
+
<CODE_SNIPPET>
- users = [
- {
- name: 'Eric',
- id: 37824,
- email: 'jellyvore@myway.com'
- },
- {
- name: 'xtof',
- id: 31337,
- email: 'b4d455h4x0r@google.com'
- },
- ...
- ];
+ {
+ "name": "Alice",
+ "id": 31502,
+ "email": "looking_glass@example.com"
+ }
</CODE_SNIPPET>
- <p>Reading these data back into memory is as simple as
- <code>eval</code>ing the string representation of the file.</p>
- <p>Similarly, <code>eval()</code> can simplify decoding RPC return
- values. For example, you might use an <code>XMLHttpRequest</code>
- to make an RPC, and in its response the server can return
- JavaScript:</p>
+
+ <BAD_CODE_SNIPPET>
+ var userInfo = eval(feed);
+ var email = userInfo['email'];
+ </BAD_CODE_SNIPPET>
+
+ <p>If the feed was modified to include malicious JavaScript code, then
+ if we use <code>eval</code> then that code will be executed.</p>
+
<CODE_SNIPPET>
- var userOnline = false;
- var user = 'nusrat';
- var xmlhttp = new XMLHttpRequest();
- xmlhttp.open('GET', 'http://chat.google.com/isUserOnline?user=' + user, false);
- xmlhttp.send('');
- // Server returns:
- // userOnline = true;
- if (xmlhttp.status == 200) {
- eval(xmlhttp.responseText);
- }
- // userOnline is now true.
+ var userInfo = JSON.parse(feed);
+ var email = userInfo['email'];
</CODE_SNIPPET>
+
+ <p>With <code>JSON.parse</code>, invalid JSON (including all executable
+ JavaScript) will cause an exception to be thrown.</p>
+
</BODY>
</STYLEPOINT>
@@ -504,6 +621,15 @@
at compile time; whitespace after the slash will result in tricky
errors; and while most script engines support this, it is not part
of ECMAScript. </p>
+ <p>Use string concatenation instead:</p>
+ <CODE_SNIPPET>
+ var myString = 'A rather long string of English text, an error message ' +
+ 'actually that just keeps going and going -- an error ' +
+ 'message to make the Energizer bunny blush (right through ' +
+ 'those Schwarzenegger shades)! Where was I? Oh yes, ' +
+ 'you\'ve got an error and all the extraneous whitespace is ' +
+ 'just gravy. Have a nice day.';
+ </CODE_SNIPPET>
</BODY>
</STYLEPOINT>
@@ -579,11 +705,11 @@
<SUMMARY>No</SUMMARY>
<BODY>
<p>Don't do this:</p>
- <CODE_SNIPPET>
+ <BAD_CODE_SNIPPET>
var f = function () {
/*@cc_on if (@_jscript) { return 2* @*/ 3; /*@ } @*/
};
- </CODE_SNIPPET>
+ </BAD_CODE_SNIPPET>
<p>Conditional Comments hinder automated tools as they can vary the
JavaScript syntax tree at runtime.</p>
</BODY>
@@ -593,27 +719,35 @@
<CATEGORY title="JavaScript Style Rules">
<STYLEPOINT title="Naming">
<SUMMARY>
- <p>In general, use <code>functionNamesLikeThis</code>,
- <code>variableNamesLikeThis</code>, <code>ClassNamesLikeThis</code>,
- <code>EnumNamesLikeThis</code>, <code>methodNamesLikeThis</code>,
- and <code>SYMBOLIC_CONSTANTS_LIKE_THIS</code>.</p>
- <p>Expand for more information.</p>
+ <p>In general, use
+ <code>functionNamesLikeThis</code>,
+ <code>variableNamesLikeThis</code>,
+ <code>ClassNamesLikeThis</code>,
+ <code>EnumNamesLikeThis</code>,
+ <code>methodNamesLikeThis</code>,
+ <code>CONSTANT_VALUES_LIKE_THIS</code>,
+ <code>foo.namespaceNamesLikeThis.bar</code>, and
+ <code>filenameslikethis.js</code>.
+ </p>
</SUMMARY>
<BODY>
<SUBSECTION title="Properties and methods">
<ul>
- <li><em>Private</em> properties, variables, and methods (in files
- or classes) should be named with a trailing
- underscore.
+ <li><em>Private</em> properties and methods should be named with a
+ trailing underscore.
</li>
- <li><em>Protected</em> properties, variables, and methods should be
+ <li><em>Protected</em> properties and methods should be
named without a trailing underscore (like public ones).</li>
</ul>
<p>For more information on <em>private</em> and <em>protected</em>,
read the section on
<a href="#Visibility__private_and_protected_fields_">
- visibility
- </a>.</p>
+ visibility</a>.
+ </p>
+
+
+
+
</SUBSECTION>
<SUBSECTION title="Method and function parameter">
@@ -629,13 +763,26 @@
</SUBSECTION>
<SUBSECTION title="Getters and Setters">
- <p>Getters and setters for properties are not required. However, if
- they are used, then getters must be named <code>getFoo()</code> and
- setters must be named <code>setFoo(value)</code>. (For boolean
- getters, <code>isFoo()</code> is also acceptable, and often sounds
- more natural.)</p>
+ <p>EcmaScript 5 getters and setters for properties are discouraged.
+ However, if they are used, then getters must not change observable
+ state.</p>
+ <BAD_CODE_SNIPPET>
+ /**
+ * WRONG -- Do NOT do this.
+ */
+ var foo = { get next() { return this.nextId++; } };
+ </BAD_CODE_SNIPPET>
</SUBSECTION>
+ <SUBSECTION title="Accessor functions">
+ <p>Getters and setters methods for properties are not required.
+ However, if they are used, then getters must be named
+ <code>getFoo()</code> and setters must be named
+ <code>setFoo(value)</code>. (For boolean getters,
+ <code>isFoo()</code> is also acceptable, and often sounds more
+ natural.)</p>
+ </SUBSECTION>
+
<SUBSECTION title="Namespaces">
<p>JavaScript has no inherent packaging or namespacing support.</p>
<p>Global name conflicts are difficult to debug, and can cause
@@ -695,7 +842,7 @@
/**
* WRONG -- Do NOT do this.
* @constructor
- * @extend {foo.hats.RoundHat}
+ * @extends {foo.hats.RoundHat}
*/
foo.hats.BowlerHat = function() {
};
@@ -712,7 +859,7 @@
/**
* @constructor
- * @extend {foo.hats.RoundHat}
+ * @extends {foo.hats.RoundHat}
*/
googleyhats.BowlerHat = function() {
...
@@ -747,7 +894,8 @@
staticHelper(new MyClass());
};
</CODE_SNIPPET>
- <p>Do not alias namespaces.</p>
+ <p>Do not create local aliases of namespaces. Namespaces should only
+ be aliased using <a href="#goog-scope">goog.scope</a>.</p>
<BAD_CODE_SNIPPET>
myapp.main = function() {
var namespace = some.long.namespace;
@@ -830,7 +978,7 @@
</STYLEPOINT>
<STYLEPOINT title="Code formatting">
- <SUMMARY>Expand for more info.</SUMMARY>
+ <SUMMARY>Expand for more information.</SUMMARY>
<BODY>
<p>We follow the <a href="cppguide.xml#Formatting">C++ formatting
rules</a> in spirit, with the following additional clarifications.</p>
@@ -854,7 +1002,7 @@
var obj = {a: 1, b: 2, c: 3}; // No space after { or before }.
</CODE_SNIPPET>
<p>Multiline array initializers and object initializers are indented
- 2 spaces, just like blocks.</p>
+ 2 spaces, with the braces on their own line, just like blocks.</p>
<CODE_SNIPPET>
// Object initializer.
var inset = {
@@ -934,8 +1082,8 @@
// ...
}
- // Parenthesis-aligned, one argument per line. Visually groups and
- // emphasizes each individual argument.
+ // Parenthesis-aligned, one argument per line. Emphasizes each
+ // individual argument.
function bar(veryDescriptiveArgumentNumberOne,
veryDescriptiveArgumentTwo,
tableModelEventHandlerProxy,
@@ -943,19 +1091,29 @@
// ...
}
</CODE_SNIPPET>
+ <p>When the function call is itself indented, you're free to start the
+ 4-space indent relative to the beginning of the original statement
+ or relative to the beginning of the current function call.
+ The following are all acceptable indentation styles.</p>
+ <CODE_SNIPPET>
+ if (veryLongFunctionNameA(
+ veryLongArgumentName) ||
+ veryLongFunctionNameB(
+ veryLongArgumentName)) {
+ veryLongFunctionNameC(veryLongFunctionNameD(
+ veryLongFunctioNameE(
+ veryLongFunctionNameF)));
+ }
+ </CODE_SNIPPET>
</SUBSECTION>
<SUBSECTION title="Passing Anonymous Functions">
<p>When declaring an anonymous function in the list of arguments for
a function call, the body of the function is indented two spaces
- from the left edge of the function call or the statement, not two
- spaces from the left edge of the function keyword. This is to make
- the body of the anonymous function easier to read (i.e. not be all
- squished up into the right half of the screen).</p>
+ from the left edge of the statement, or two spaces from the left
+ edge of the function keyword. This is to make the body of the
+ anonymous function easier to read (i.e. not be all squished up into
+ the right half of the screen).</p>
<CODE_SNIPPET>
- var names = items.map(function(item) {
- return item.name;
- });
-
prefix.something.reallyLongFunctionName('whatever', function(a1, a2) {
if (a1.equals(a2)) {
someOtherLongFunctionName(a1);
@@ -963,17 +1121,81 @@
andNowForSomethingCompletelyDifferent(a2.parrot);
}
});
+
+ var names = prefix.something.myExcellentMapFunction(
+ verboselyNamedCollectionOfItems,
+ function(item) {
+ return item.name;
+ });
</CODE_SNIPPET>
</SUBSECTION>
- <SUBSECTION title="More Indentation">
- <p>In fact, except for
- <a href="#Array_and_Object_literals">
- array and object initializers
- </a>, and passing anonymous functions, all wrapped lines
- should be indented either left-aligned to the expression above, or
- indented four spaces, not indented two spaces.</p>
+ <SUBSECTION title="Aliasing with goog.scope">
+ <a name="goog-scope"/>
+ <p>
+ <a href="https://docs.google.com/document/pub?id=1ETFAuh2kaXMVL-vafUYhaWlhl6b5D9TOvboVg7Zl68Y"><code>goog.scope</code></a>
+ may be used to shorten references to
+ namespaced symbols in programs using
+ <a href="http://code.google.com/closure/library/">the Closure
+ Library</a>.</p>
+ <p>Only one <code>goog.scope</code> invocation may be added per
+ file. Always place it in the global scope.</p>
+ <p>The opening <code>goog.scope(function() {</code> invocation
+ must be preceded by exactly one blank line and follow any
+ <code>goog.provide</code> statements, <code>goog.require</code>
+ statements, or top-level comments. The invocation must be closed on
+ the last line in the file. Append <code>// goog.scope</code> to the
+ closing statement of the scope. Separate the comment from the
+ semicolon by two spaces.</p>
+ <p>Similar to C++ namespaces, do not indent under goog.scope
+ declarations. Instead, continue from the 0 column.</p>
+ <p>Only alias names that will not be re-assigned to another object
+ (e.g., most constructors, enums, and namespaces). Do not do
+ this (see below for how to alias a constructor):</p>
+ <BAD_CODE_SNIPPET>
+ goog.scope(function() {
+ var Button = goog.ui.Button;
+
+ Button = function() { ... };
+ ...
+ </BAD_CODE_SNIPPET>
+
+ <p>Names must be the same as the last property of the global that they
+ are aliasing.</p>
+
<CODE_SNIPPET>
+ goog.provide('my.module.SomeType');
+
+ goog.require('goog.dom');
+ goog.require('goog.ui.Button');
+
+ goog.scope(function() {
+ var Button = goog.ui.Button;
+ var dom = goog.dom;
+
+ // Alias new types <b>after</b> the constructor declaration.
+ my.module.SomeType = function() { ... };
+ var SomeType = my.module.SomeType;
+
+ // Declare methods on the prototype as usual:
+ SomeType.prototype.findButton = function() {
+ // Button as aliased above.
+ this.button = new Button(dom.getElement('my-button'));
+ };
+ ...
+ }); // goog.scope
+ </CODE_SNIPPET>
+ </SUBSECTION>
+ <SUBSECTION title="Indenting wrapped lines">
+ <p>Except for <a href="#Array_and_Object_literals">array literals,
+ object literals</a>, and anonymous functions, all wrapped lines
+ should be indented either left-aligned to a sibling expression
+ above, or four spaces (not two spaces) deeper than a parent
+ expression (where "sibling" and "parent" refer to parenthesis
+ nesting level).
+ </p>
+
+ <CODE_SNIPPET>
someWonderfulHtml = '<div class="' + getClassesForWonderfulHtml()'">' +
getEvenMoreHtml(someReallyInterestingValues, moreValues,
evenMoreParams, 'a duck', true, 72,
@@ -983,9 +1205,14 @@
thisIsAVeryLongVariableName =
hereIsAnEvenLongerOtherFunctionNameThatWillNotFitOnPrevLine();
- thisIsAVeryLongVariableName = 'expressionPartOne' + someMethodThatIsLong() +
- thisIsAnEvenLongerOtherFunctionNameThatCannotBeIndentedMore();
+ thisIsAVeryLongVariableName = siblingOne + siblingTwo + siblingThree +
+ siblingFour + siblingFive + siblingSix + siblingSeven +
+ moreSiblingExpressions + allAtTheSameIndentationLevel;
+ thisIsAVeryLongVariableName = operandOne + operandTwo + operandThree +
+ operandFour + operandFive * (
+ aNestedChildExpression + shouldBeIndentedMore);
+
someValue = this.foo(
shortArg,
'Some really long string arg - this is a pretty common case, actually.',
@@ -1013,10 +1240,12 @@
</CODE_SNIPPET>
</SUBSECTION>
<SUBSECTION title="Binary and Ternary Operators">
- <p>Always put the operator on the preceding line, so that you don't
- have to think about implicit semi-colon insertion issues. Otherwise,
+ <p>Always put the operator on the preceding line. Otherwise,
line breaks and indentation follow the same rules as in other
- Google style guides.</p>
+ Google style guides. This operator placement was initially agreed
+ upon out of concerns about automatic semicolon insertion. In fact,
+ semicolon insertion cannot happen before a binary operator, but new
+ code should stick to this style for consistency.</p>
<CODE_SNIPPET>
var x = a ? b : c; // All on one line if it will fit.
@@ -1029,6 +1258,12 @@
moreComplicatedB :
moreComplicatedC;
</CODE_SNIPPET>
+ <p>This includes the dot operator.</p>
+ <CODE_SNIPPET>
+ var x = foo.bar().
+ doSomething().
+ doSomethingElse();
+ </CODE_SNIPPET>
</SUBSECTION>
</BODY>
</STYLEPOINT>
@@ -1041,7 +1276,8 @@
<p>Never use parentheses for unary operators such as
<code>delete</code>, <code>typeof</code> and <code>void</code> or
after keywords such as <code>return</code>, <code>throw</code> as
- well as others (<code>case</code>, in or <code>new</code>).</p>
+ well as others (<code>case</code>, <code>in</code> or
+ <code>new</code>).</p>
</BODY>
</STYLEPOINT>
@@ -1063,7 +1299,12 @@
<p>We recommend the use of the JSDoc annotations <code>@private</code> and
<code>@protected</code> to indicate visibility levels for classes,
functions, and properties.</p>
-
+ <p>The --jscomp_warning=visibility compiler flag turns on compiler
+ warnings for visibility violations. See
+ <a href="http://code.google.com/p/closure-compiler/wiki/Warnings">
+ Closure Compiler
+ Warnings</a>.
+ </p>
<p><code>@private</code> global variables and functions are only
accessible to code in the same file.</p>
<p>Constructors marked <code>@private</code> may only be instantiated by
@@ -1102,26 +1343,31 @@
<p>Note that these semantics differ from those of C++ and Java, in that
they grant private and protected access to all code in the same file,
not just in the same class or class hierarchy. Also, unlike in C++,
- private properties cannot be overriden by a subclass.
+ private properties cannot be overridden by a subclass.
</p>
<CODE_SNIPPET>
// File 1.
/** @constructor */
- AA_PublicClass = function() {
+ AA_PublicClass = function() {
+ /** @private */
+ this.privateProp_ = 2;
+
+ /** @protected */
+ this.protectedProp = 4;
};
/** @private */
AA_PublicClass.staticPrivateProp_ = 1;
- /** @private */
- AA_PublicClass.prototype.privateProp_ = 2;
-
/** @protected */
AA_PublicClass.staticProtectedProp = 31;
+ /** @private */
+ AA_PublicClass.prototype.privateMethod_ = function() {};
+
/** @protected */
- AA_PublicClass.prototype.protectedProp = 4;
+ AA_PublicClass.prototype.protectedMethod = function() {};
// File 2.
@@ -1153,31 +1399,37 @@
return this.protectedProp;
};
</CODE_SNIPPET>
+
+ <p>Notice that in JavaScript, there is no distinction between a type
+ (like <code>AA_PrivateClass_</code>) and the constructor for that
+ type. There is no way to express both that a type is public and its
+ constructor is private (because the constructor could easily be aliased
+ in a way that would defeat the privacy check).</p>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="JavaScript Types">
<SUMMARY>Encouraged and enforced by the compiler.</SUMMARY>
<BODY>
+ <a name="JsTypes"/>
<p>When documenting a type in JSDoc, be as specific and accurate as
- possible. The types we support are
+ possible. The types we support are based on the
<a href="http://wiki.ecmascript.org/doku.php?id=spec:spec">
- JS2
- </a>
- style types and JS1.x types.</p>
+ EcmaScript 4 spec</a>.</p>
<SUBSECTION title="The JavaScript Type Language">
- <p>The JS2 proposal contained a language for specifying JavaScript
+ <p>The ES4 proposal contained a language for specifying JavaScript
types. We use this language in JsDoc to express the types of
function parameters and return values.</p>
- <p>As the JS2 proposal has evolved, this language has changed. The
+ <p>As the ES4 proposal has evolved, this language has changed. The
compiler still supports old syntaxes for types, but those syntaxes
are deprecated.</p>
+ <p/>
<table border="1" style="border-collapse:collapse" cellpadding="4">
<thead>
<tr>
- <th>Operator Name</th>
+ <th>Syntax Name</th>
<th>Syntax</th>
<th>Description</th>
<th>Deprecated Syntaxes</th>
@@ -1185,16 +1437,64 @@
</thead>
<tbody>
<tr>
- <td>Type Name</td>
+ <td>Primitive Type</td>
<td>
- <code>{boolean}</code>, <code>{Window}</code>,
- <code>{goog.ui.Menu}</code>
+ There are 5 primitive types in JavaScript:
+ <code>{null}</code>,
+ <code>{undefined}</code>,
+ <code>{boolean}</code>,
+ <code>{number}</code>, and
+ <code>{string}</code>.
</td>
<td>Simply the name of a type.</td>
<td/>
</tr>
<tr>
+ <td>Instance Type</td>
+ <td>
+ <code>{Object}</code><br/>
+ An instance of Object or null.<p/>
+ <code>{Function}</code><br/>
+ An instance of Function or null.<p/>
+ <code>{EventTarget}</code><br/>
+ An instance of a constructor that implements the EventTarget
+ interface, or null.
+ </td>
+ <td>An instance of a constructor or interface function.<p/>
+
+ Constructor functions are functions defined with the
+ <code>@constructor</code> JSDoc tag.
+ Interface functions are functions defined with the
+ <code>@interface</code> JSDoc tag.<p/>
+
+ By default, instance types will accept null. This is the only
+ type syntax that makes the type nullable. Other type syntaxes
+ in this table will not accept null.
+ </td>
+ <td/>
+ </tr>
+
+ <tr>
+ <td>Enum Type</td>
+ <td>
+ <code>{goog.events.EventType}</code><br/>
+ One of the properties of the object literal initializer
+ of <code>goog.events.EventType</code>.
+ </td>
+ <td>An enum must be initialized as an object literal, or as
+ an alias of another enum, annotated with the <code>@enum</code>
+ JSDoc tag. The properties of this literal are the instances
+ of the enum. The syntax of the enum is defined
+ <a href="#enums">below</a>.<p/>
+
+ Note that this is one of the few things in our type system
+ that were not in the ES4 spec.
+ </td>
+ <td/>
+ </tr>
+
+ <tr>
<td>Type Application</td>
<td>
<code>{Array.&lt;string&gt;}</code><br/>An array of strings.<p/>
@@ -1202,7 +1502,7 @@
<br/>An object in which the keys are strings and the values
are numbers.
</td>
- <td>Patameterizes a type, by applying a set of type arguments
+ <td>Parameterizes a type, by applying a set of type arguments
to that type. The idea is analogous to generics in Java.
</td>
<td/>
@@ -1213,41 +1513,27 @@
<td>
<code>{(number|boolean)}</code><br/>A number or a boolean.
</td>
- <td>Indicates that a value might have type A OR type B.</td>
- <td>
- <code>{(number,boolean)}</code>,
- <code>{number|boolean}</code>,
- <code>{(number||boolean)}</code>
- </td>
- </tr>
+ <td>Indicates that a value might have type A OR type B.<p/>
- <tr>
- <td>Record Type</td>
- <td>
- <code>{{myNum: number, myObject}}</code>
- <br/>An anonymous type with the given type members.
+ The parentheses may be omitted at the top-level
+ expression, but the parentheses should be included in
+ sub-expressions to avoid ambiguity.<br/>
+ <code>{number|boolean}</code><br/>
+ <code>{function(): (number|boolean)}</code>
</td>
<td>
- <p>Indicates that the value has the specified members with the
- specified types. In this case, <code>myNum</code> with a
- type <code>number</code> and <code>myObject</code> with any
- type.</p>
- <p>Notice that the braces are part of the type syntax. For
- example, to denote an <code>Array</code> of objects that
- have a <code>length</code> property, you might write
- <code>Array.&lt;{length}&gt;</code>.</p>
+ <code>{(number,boolean)}</code>,<br/>
+ <code>{(number||boolean)}</code>
</td>
- <td/>
</tr>
<tr>
<td>Nullable type</td>
<td>
- <code>{?number}</code><br/> A number or NULL.
+ <code>{?number}</code><br/> A number or null.
</td>
- <td>Indicates that a value is type A or <code>null</code>.
- By default, all object types are nullable.
- NOTE: Function types are not nullable.
+ <td>Shorthand for the union of the null type with any
+ other type. This is just syntactic sugar.
</td>
<td>
<code>{number?}</code>
@@ -1260,9 +1546,8 @@
<code>{!Object}</code><br/> An Object, but never the
<code>null</code> value.
</td>
- <td>Indicates that a value is type A and not null. By default,
- all value types (boolean, number, string, and undefined) are
- not nullable.
+ <td>Filters null out of nullable types. Most often used
+ with instance types, which are nullable by default.
</td>
<td>
<code>{Object!}</code>
@@ -1270,6 +1555,25 @@
</tr>
<tr>
+ <td>Record Type</td>
+ <td>
+ <code>{{myNum: number, myObject}}</code>
+ <br/>An anonymous type with the given type members.
+ </td>
+ <td>
+ <p>Indicates that the value has the specified members with the
+ specified types. In this case, <code>myNum</code> with a
+ type <code>number</code> and <code>myObject</code> with any
+ type.</p>
+ <p>Notice that the braces are part of the type syntax. For
+ example, to denote an <code>Array</code> of objects that
+ have a <code>length</code> property, you might write
+ <code>Array.&lt;{length}&gt;</code>.</p>
+ </td>
+ <td/>
+ </tr>
+
+ <tr>
<td>Function Type</td>
<td>
<code>{function(string, boolean)}</code><br/>
@@ -1302,6 +1606,18 @@
</tr>
<tr>
+ <td>Function <code>new</code> Type</td>
+ <td>
+ <code>{function(new:goog.ui.Menu, string)}</code><br/>
+ A constructor that takes one argument (a string), and
+ creates a new instance of goog.ui.Menu when called
+ with the 'new' keyword.
+ </td>
+ <td>Specifies the constructed type of a constructor.</td>
+ <td/>
+ </tr>
+
+ <tr>
<td>Variable arguments</td>
<td>
<code>{function(string, ...[number]): number}</code><br/>
@@ -1329,7 +1645,7 @@
</tr>
<tr>
- <td>Function <a href="optional">optional arguments</a></td>
+ <td>Function <a href="#optional">optional arguments</a></td>
<td>
<code>{function(?string=, number=)}</code><br/>
A function that takes one optional, nullable string and one
@@ -1343,7 +1659,7 @@
<tr>
<td>
<a name="optional-arg-annotation"/>
- Function <a href="optional">optional arguments</a>
+ Function <a href="#optional">optional arguments</a>
(in <code>@param</code> annotations)
</td>
<td>
@@ -1361,6 +1677,14 @@
<td>Indicates that the variable can take on any type.</td>
<td/>
</tr>
+
+ <tr>
+ <td>The UNKNOWN type</td>
+ <td><code>{?}</code></td>
+ <td>Indicates that the variable can take on any type,
+ and the compiler should not type-check any uses of it.</td>
+ <td/>
+ </tr>
</tbody>
</table>
</SUBSECTION>
@@ -1586,12 +1910,12 @@
</CODE_SNIPPET>
</td>
<td>
- An Object in which the keys are numbers and the values
- are strings. <p/>Note that in JavaScript, the keys are always
- implicitly coverted to strings, so
+ An Object in which the keys are numbers and the values are
+ strings. <p/>Note that in JavaScript, the keys are always
+ implicitly converted to strings, so
<code>obj['1'] == obj[1]</code>.
- So the key wil always be a string in for...in loops. But the
- compiler will verify the type if the key when indexing into
+ So the key will always be a string in for...in loops. But the
+ compiler will verify the type of the key when indexing into
the object.
</td>
</tr>
@@ -1625,7 +1949,7 @@
</tr>
<tr>
- <td>SomeClass</td>
+ <td><a name="constructor-tag">SomeClass</a></td>
<td>
<CODE_SNIPPET>
/** @constructor */
@@ -1669,12 +1993,16 @@
<CODE_SNIPPET>
/** @enum {string} */
project.MyEnum = {
+ /** The color blue. */
BLUE: '#0000dd',
+ /** The color red. */
RED: '#dd0000'
};
</CODE_SNIPPET>
</td>
- <td><a href="#enums">Enumeration</a></td>
+ <td><a name="enums">Enumeration</a><p/>
+ JSDoc comments on enum values are optional.
+ </td>
</tr>
<tr>
@@ -1710,6 +2038,17 @@
</table>
</SUBSECTION>
+ <SUBSECTION title="Type Casts">
+ <p>In cases where type-checking doesn't accurately infer the type of
+ an expression, it is possible to add a type cast comment by adding a
+ type annotation comment and enclosing the expression in
+ parentheses. The parentheses are required.</p>
+
+ <CODE_SNIPPET>
+ /** @type {number} */ (x)
+ </CODE_SNIPPET>
+ </SUBSECTION>
+
<SUBSECTION title="Nullable vs. Optional Parameters and Properties">
<a name="optional"/>
<p>Because JavaScript is a loosely-typed language, it is very
@@ -1717,10 +2056,8 @@
nullable, and undefined function parameters and class
properties.</p>
- <p>Object types (also known as reference types) are nullable by
- default. NOTE: Function types are not nullable by default. An
- object is defined as anything except a string, number, boolean,
- undefined, or null. For example, the following declaration</p>
+ <p>Instances of classes and interfaces are nullable by default.
+ For example, the following declaration</p>
<CODE_SNIPPET>
/**
@@ -1812,162 +2149,109 @@
};
</CODE_SNIPPET>
</SUBSECTION>
- </BODY>
- </STYLEPOINT>
- <STYLEPOINT title="Comments">
- <SUMMARY>Use JSDoc</SUMMARY>
- <BODY>
- <p>We use
- <a href="http://code.google.com/p/jsdoc-toolkit/">
- JSDoc
- </a>
- comments to document files, classes, methods and properties. Inline
- comments should be of the // variety. Additionally, we follow the
- <a href="cppguide.xml#Comments">
- C++ style for comments
- </a> in spirit. This means you should have:
- </p>
- <ul>
- <li>copyright and authorship notice,</li>
- <li>a top-level (file-level) comment designed to orient readers
- unfamiliar with the code to what's in this file (e.g., a
- one-paragraph summary of what the major pieces are, how they fit
- together, and with what they interact),</li>
- <li>class, function, variable, and implementation comments as
- necessary,</li>
- <li>an indication of the browsers in which the code is expected to
- work (if applicable), and</li>
- <li>proper capitalization, punctuation, and spelling.</li>
- </ul>
+ <SUBSECTION title="Typedefs">
+ <a name="Typedefs"/>
+ <p>Sometimes types can get complicated. A function that accepts
+ content for an Element might look like:</p>
- <p>Avoid sentence fragments. Start sentences with a properly
- capitalized word, and end them with punctuation.</p>
-
- <p>Pretend there's some novice programmer that's going to come along and
- have to maintain the code after you. There very well just might
- be!</p>
-
- <p>There are now many compiler passes that extract type information from
- JSDoc, in order to provide better code validation, removal, and
- compression. It is, therefore, very important that you use full and
- correct JSDoc.</p>
-
- <SUBSECTION title="Top/File-Level Comments">
- <p>
-
- The top level comment is designed
- to orient readers unfamiliar with the code to what is in this file.
- It should provide a description of the file's contents, its
- author(s), and any dependencies or compatibility information. As an
- example:</p>
-
<CODE_SNIPPET>
- // Copyright 2009 Google Inc. All Rights Reserved.
-
/**
- * @fileoverview Description of file, its uses and information
- * about its dependencies.
- * @author user@google.com (Firstname Lastname)
+ * @param {string} tagName
+ * @param {(string|Element|Text|Array.&lt;Element&gt;|Array.&lt;Text&gt;)} contents
+ * @return {!Element}
*/
+ goog.createElement = function(tagName, contents) {
+ ...
+ };
</CODE_SNIPPET>
-
- </SUBSECTION>
+ <p>You can define commonly used type expressions with a
+ <code>@typedef</code> tag. For example,</p>
- <SUBSECTION title="Class Comments">
- <p>Classes must be documented with a description and usage.
- The constructor parameters must also be documented.
- If the class inherits from another class,
- that should be documented with an <code>@extends</code> tag.
- If the class implements an interface,
- that should be documented with an <code>@implements</code> tag.
- </p>
+ <CODE_SNIPPET>
+ /** @typedef {(string|Element|Text|Array.&lt;Element&gt;|Array.&lt;Text&gt;)} */
+ goog.ElementContent;
- <CODE_SNIPPET>
/**
- * Class making something fun and easy.
- * @param {string} arg1 An argument that makes this more interesting.
- * @param {Array.&lt;number&gt;} arg2 List of numbers to be processed.
- * @constructor
- * @extends {goog.Disposable}
+ * @param {string} tagName
+ * @param {goog.ElementContent} contents
+ * @return {!Element}
*/
- project.MyClass = function(arg1, arg2) {
- // ...
+ goog.createElement = function(tagName, contents) {
+ ...
};
- goog.inherits(project.MyClass, goog.Disposable);
</CODE_SNIPPET>
</SUBSECTION>
- <SUBSECTION title="Method and Function Comments">
- <p>A description must be provided along with parameters. Use full
- sentences. Method descriptions should start with a sentence written
- in the third person declarative voice.</p>
+ <SUBSECTION title="Template types">
+ <a name="Template_types"/>
+ <p>The compiler has limited support for template types. It can only
+ infer the type of <code>this</code> inside an anonymous function
+ literal from the type of the <code>this</code> argument and whether the
+ <code>this</code> argument is missing.</p>
<CODE_SNIPPET>
/**
- * Converts text to some completely different text.
- * @param {string} arg1 An argument that makes this more interesting.
- * @return {string} Some return value.
+ * @param {function(this:T, ...)} fn
+ * @param {T} thisObj
+ * @param {...*} var_args
+ * @template T
*/
- project.MyClass.prototype.someMethod = function(arg1) {
- // ...
+ goog.bind = function(fn, thisObj, var_args) {
+ ...
};
-
- /**
- * Operates on an instance of MyClass and returns something.
- * @param {project.MyClass} obj Instance of MyClass which leads to a long
- * comment that needs to be wrapped to two lines.
- * @return {boolean} Whether something occured.
- */
- function PR_someMethod(obj) {
- // ...
- }
+ // Possibly generates a missing property warning.
+ goog.bind(function() { this.someProperty; }, new SomeClass());
+ // Generates an undefined this warning.
+ goog.bind(function() { this.someProperty; });
</CODE_SNIPPET>
+ </SUBSECTION>
+ </BODY>
+ </STYLEPOINT>
- <p>For simple getters that take no parameters, the description can be
- omitted.</p>
+ <STYLEPOINT title="Comments">
+ <SUMMARY>Use JSDoc</SUMMARY>
+ <BODY>
+ <p>
+ We follow the
+ <a href="cppguide.xml#Comments">
+ C++ style for comments</a> in spirit.
+ </p>
- <CODE_SNIPPET>
- /**
- * @return {Element} The element for the component.
- */
- goog.ui.Component.prototype.getElement = function() {
- return this.element_;
- };
- </CODE_SNIPPET>
- </SUBSECTION>
+ <p>All files, classes, methods and properties should be documented with
+ <a href="http://code.google.com/p/jsdoc-toolkit/">JSDoc</a>
+ comments with the appropriate <a href="#JSDoc_Tag_Reference">tags</a>
+ and <a href="#JsTypes">types</a>. Textual descriptions for properties,
+ methods, method parameters and method return values should be included
+ unless obvious from the property, method, or parameter name.
+ </p>
- <SUBSECTION title="Property Comments">
- <p>It is also nice to have comments for properties.</p>
+ <p>Inline comments should be of the <code>//</code> variety.</p>
- <CODE_SNIPPET>
- /**
- * Maximum number of things per pane.
- * @type {number}
- */
- project.MyClass.prototype.someProperty = 4;
- </CODE_SNIPPET>
- </SUBSECTION>
+ <p>Complete sentences are recommended but not required.
+ Complete sentences should use appropriate capitalization
+ and punctuation.</p>
- <SUBSECTION title="Type Cast Comments">
- <p>In cases where type-checking doesn't accurately infer the type of
- an expression, it is possible to add a type cast comment by adding a
- type annotation comment and enclosing the expression in
- parenthesis. The parentheses are required, and may surround the type
- annotation comment as well.</p>
+ <SUBSECTION title="Comment Syntax">
+ <p>The JSDoc syntax is based on
+ <a href="http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html">
+ JavaDoc</a>. Many tools extract metadata from JSDoc comments to
+ perform code validation and optimizations. These comments must be
+ well-formed.</p>
<CODE_SNIPPET>
- /** @type {number} */ (x)
- (/** @type {number} */ x)
+ /**
+ * A JSDoc comment should begin with a slash and 2 asterisks.
+ * Inline tags should be enclosed in braces like {@code this}.
+ * @desc Block tags should always start on their own line.
+ */
</CODE_SNIPPET>
</SUBSECTION>
<SUBSECTION title="JSDoc Indentation">
- <p>If you have to line break a <code>@param</code>,
- <code>@return</code>, <code>@supported</code>, <code>@this</code> or
- <code>@deprecated</code> you should treat this as breaking a code
- statement and indent it four spaces.</p>
+ <p>If you have to line break a block tag, you should treat this as
+ breaking a code statement and indent it four spaces.</p>
<CODE_SNIPPET>
/**
@@ -1982,12 +2266,11 @@
};
</CODE_SNIPPET>
- <p>You should not indent the <code>@fileoverview</code> command.</p>
+ <p>You should not indent the <code>@fileoverview</code> command. You do not have to
+ indent the <code>@desc</code> command.</p>
<p>Even though it is not preferred, it is also acceptable to line up
- the description. This has the side effect that you will have to
- realign the text every time you change a variable name so this will
- soon get your code out of sync.</p>
+ the description.</p>
<CODE_SNIPPET>
/**
@@ -2003,269 +2286,412 @@
</CODE_SNIPPET>
</SUBSECTION>
- <SUBSECTION title="Enums">
- <a name="enums"/>
+ <SUBSECTION title="HTML in JSDoc">
+ <p>Like JavaDoc, JSDoc supports many HTML tags, like &lt;code&gt;,
+ &lt;pre&gt;, &lt;tt&gt;, &lt;strong&gt;, &lt;ul&gt;, &lt;ol&gt;,
+ &lt;li&gt;, &lt;a&gt;, and others.</p>
+
+ <p>This means that plaintext formatting is not respected. So, don't
+ rely on whitespace to format JSDoc:</p>
+
+ <BAD_CODE_SNIPPET>
+ /**
+ * Computes weight based on three factors:
+ * items sent
+ * items received
+ * last timestamp
+ */
+ </BAD_CODE_SNIPPET>
+
+ <p>It'll come out like this:</p>
+
+ <BAD_CODE_SNIPPET>
+ Computes weight based on three factors: items sent items received last timestamp
+ </BAD_CODE_SNIPPET>
+
+ <p>Instead, do this:</p>
+
<CODE_SNIPPET>
/**
- * Enum for tri-state values.
- * @enum {number}
+ * Computes weight based on three factors:
+ * &lt;ul&gt;
+ * &lt;li&gt;items sent
+ * &lt;li&gt;items received
+ * &lt;li&gt;last timestamp
+ * &lt;/ul&gt;
*/
- project.TriState = {
- TRUE: 1,
- FALSE: -1,
- MAYBE: 0
- };
</CODE_SNIPPET>
- <p>Note that enums are also valid <a href="#JavaScript_Types">types</a>
- and thus can be used as parameter types, etc.</p>
+ The <a href="http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html">
+ JavaDoc</a> style guide is a useful resource on how to write
+ well-formed doc comments.
+ </SUBSECTION>
+ <SUBSECTION title="Top/File-Level Comments">
+ <p>
+
+ A <a href="copyright.html">copyright notice</a> and author information are optional.
+ File overviews are generally recommended whenever a file consists of
+ more than a single class definition. The top level comment is
+ designed to orient readers unfamiliar with the code to what is in
+ this file. If present, it should provide a description of the
+ file's contents and any dependencies or compatibility information.
+ As an example:
+ </p>
+
<CODE_SNIPPET>
/**
- * Sets project state.
- * @param {project.TriState} state New project state.
+ * @fileoverview Description of file, its uses and information
+ * about its dependencies.
*/
- project.setState = function(state) {
- // ...
- };
</CODE_SNIPPET>
+
+
</SUBSECTION>
- <SUBSECTION title="Typedefs">
- <p>Sometimes types can get complicated. A function that accepts
- content for an Element might look like:</p>
+ <SUBSECTION title="Class Comments">
+ <p>Classes must be documented with a description and a
+ <a href="#constructor-tag">type tag that
+ identifies the constructor</a>.
+ </p>
<CODE_SNIPPET>
/**
- * @param {string} tagName
- * @param {(string|Element|Text|Array.&lt;Element&gt;|Array.&lt;Text&gt;)} contents
- * @return {Element}
+ * Class making something fun and easy.
+ * @param {string} arg1 An argument that makes this more interesting.
+ * @param {Array.&lt;number&gt;} arg2 List of numbers to be processed.
+ * @constructor
+ * @extends {goog.Disposable}
*/
- goog.createElement = function(tagName, contents) {
- ...
+ project.MyClass = function(arg1, arg2) {
+ // ...
};
+ goog.inherits(project.MyClass, goog.Disposable);
</CODE_SNIPPET>
+ </SUBSECTION>
- <p>You can define commonly used type expressions with a
- <code>@typedef</code> tag. For example,</p>
-
+ <SUBSECTION title="Method and Function Comments">
+ <p>Parameter and return types should be documented. The method
+ description may be omitted if it is obvious from the parameter
+ or return type descriptions. Method descriptions should start
+ with a sentence written in the third person declarative voice.</p>
<CODE_SNIPPET>
- /** @typedef {(string|Element|Text|Array.&lt;Element&gt;|Array.&lt;Text&gt;)} */
- goog.ElementContent;
-
/**
- * @param {string} tagName
- * @param {goog.ElementContent} contents
- * @return {Element}
- */
- goog.createElement = function(tagName, contents) {
- ...
- };
+ * Operates on an instance of MyClass and returns something.
+ * @param {project.MyClass} obj Instance of MyClass which leads to a long
+ * comment that needs to be wrapped to two lines.
+ * @return {boolean} Whether something occurred.
+ */
+ function PR_someMethod(obj) {
+ // ...
+ }
</CODE_SNIPPET>
</SUBSECTION>
-
+ <SUBSECTION title="Property Comments">
+ <CODE_SNIPPET>
+ /** @constructor */
+ project.MyClass = function() {
+ /**
+ * Maximum number of things per pane.
+ * @type {number}
+ */
+ this.someProperty = 4;
+ }
+ </CODE_SNIPPET>
+ </SUBSECTION>
<SUBSECTION title="JSDoc Tag Reference">
+ <a name="JSDoc_Tag_Reference"/>
+ <p/>
<table border="1" style="border-collapse:collapse" cellpadding="4">
<thead>
<tr>
<th>Tag</th>
<th>Template &amp; Examples</th>
<th>Description</th>
- <th>Type-Checking Support</th>
</tr>
</thead>
<tbody>
<tr>
- <td><a name="tag-param">@param</a></td>
<td>
- <tt>@param {Type} varname Description</tt>
+ <a name="tag-author">@author</a>
+
+ </td>
+ <td>
+ <code>@author username@google.com (first last)</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
- * Queries a Baz for items.
- * @param {number} groupNum Subgroup id to query.
- * @param {string|number|null} term An itemName,
- * or itemId, or null to search everything.
+ * @fileoverview Utilities for handling textareas.
+ * @author kuth@google.com (Uthur Pendragon)
*/
- goog.Baz.prototype.query = function(groupNum, term) {
- // ...
- };
</CODE_SNIPPET>
</td>
<td>
- Used with method, function and constructor calls to document
- the arguments of a function.
+ Document the author of a file or the owner of a test,
+ generally only used in the <code>@fileoverview</code> comment.
+
</td>
- <td>Fully supported.</td>
</tr>
+
+
<tr>
- <td><a name="tag-return">@return</a></td>
+ <td><a name="tag-code">@code</a></td>
<td>
- <tt>@return {Type} Description</tt>
+ <code>{@code ...}</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
- * @return {string} The hex ID of the last item.
+ * Moves to the next position in the selection.
+ * Throws {@code goog.iter.StopIteration} when it
+ * passes the end of the range.
+ * @return {Node} The node at the next position.
*/
- goog.Baz.prototype.getLastId = function() {
+ goog.dom.RangeIterator.prototype.next = function() {
// ...
- return id;
};
</CODE_SNIPPET>
</td>
<td>
- Used with method and function calls to document the return
- type. When writing descriptions for boolean parameters,
- prefer "Whether the component is visible" to "True if the
- component is visible, false otherwise". If there is no return
- value, do not use an <code>@return</code> tag.
+ Indicates that a term in a JSDoc description is code so it may
+ be correctly formatted in generated documentation.
</td>
- <td>Fully supported.</td>
</tr>
<tr>
+ <td><a name="tag-const">@const</a></td>
<td>
- <a name="tag-author">@author</a>
-
+ <code>@const</code><br/>
+ <code>@const {type}</code>
+ <p><i>For example:</i></p>
+ <CODE_SNIPPET>
+ /** @const */ var MY_BEER = 'stout';
+
+ /**
+ * My namespace's favorite kind of beer.
+ * @const {string}
+ */
+ mynamespace.MY_BEER = 'stout';
+
+ /** @const */ MyClass.MY_BEER = 'stout';
+
+ /**
+ * Initializes the request.
+ * @const
+ */
+ mynamespace.Request.prototype.initialize = function() {
+ // This method cannot be overridden in a subclass.
+ };
+ </CODE_SNIPPET>
</td>
<td>
- <tt>@author username@google.com (first last)</tt>
+ <p>Marks a variable (or property) as read-only and suitable
+ for inlining.</p>
+
+ <p>A <code>@const</code> variable is an immutable pointer to
+ a value. If a variable or property marked as
+ <code>@const</code> is overwritten, JSCompiler will give
+ warnings.</p>
+
+ <p>The type declaration of a constant value can be omitted
+ if it can be clearly inferred. An additional comment about
+ the variable is optional.</p>
+
+ <p>When <code>@const</code> is applied to a method, it
+ implies the method is not only not overwritable, but also
+ that the method is <em>finalized</em> —
+ not overridable in subclasses.</p>
+
+ <p>For more on <code>@const</code>, see the
+ <a href="#Constants">Constants</a> section.</p>
+
+ </td>
+ </tr>
+
+ <tr>
+ <td><a name="tag-constructor">@constructor</a></td>
+ <td>
+ <code>@constructor</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
- * @fileoverview Utilities for handling textareas.
- * @author kuth@google.com (Uthur Pendragon)
+ * A rectangle.
+ * @constructor
*/
+ function GM_Rect() {
+ ...
+ }
</CODE_SNIPPET>
</td>
<td>
- Document the author of a file or the owner of a test,
- generally only used in the <code>@fileoverview</code> comment.
-
+ Used in a class's documentation to indicate the constructor.
</td>
- <td>Unrelated to type checking.</td>
</tr>
<tr>
- <td><a name="tag-see">@see</a></td>
+ <td><a name="tag-define">@define</a></td>
<td>
- <tt>@see Link</tt>
+ <code>@define {Type} description</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
+ /** @define {boolean} */
+ var TR_FLAGS_ENABLE_DEBUG = true;
+
/**
- * Adds a single item, recklessly.
- * @see #addSafely
- * @see goog.Collect
- * @see goog.RecklessAdder#add
- ...
+ * @define {boolean} Whether we know at compile-time that
+ * the browser is IE.
+ */
+ goog.userAgent.ASSUME_IE = false;
</CODE_SNIPPET>
</td>
- <td>Reference a lookup to another class function or method.</td>
- <td>Unrelated to type checking.</td>
+ <td>
+ Indicates a constant that can be overridden by the compiler at
+ compile-time. In the example, the compiler flag
+ <code>--define='goog.userAgent.ASSUME_IE=true'</code>
+ could be specified in the BUILD file to indicate that the
+ constant <code>goog.userAgent.ASSUME_IE</code> should be replaced
+ with <code>true</code>.
+ </td>
</tr>
<tr>
- <td><a name="tag-fileoverview">@fileoverview</a></td>
+ <td><a name="tag-deprecated">@deprecated</a></td>
<td>
- <tt>@fileoverview Description</tt>
+ <code>@deprecated Description</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
- * @fileoverview Utilities for doing things that require this very long
- * but not indented comment.
- * @author kuth@google.com (Uthur Pendragon)
+ * Determines whether a node is a field.
+ * @return {boolean} True if the contents of
+ * the element are editable, but the element
+ * itself is not.
+ * @deprecated Use isField().
*/
+ BN_EditUtil.isTopEditableField = function(node) {
+ // ...
+ };
</CODE_SNIPPET>
</td>
- <td>Makes the comment block provide file level information.</td>
- <td>Unrelated to type checking.</td>
+ <td>
+ Used to tell that a function, method or property should not be
+ used any more. Always provide instructions on what callers
+ should use instead.
+ </td>
</tr>
<tr>
- <td><a name="tag-constructor">@constructor</a></td>
+ <td><a name="tag-dict">@dict</a></td>
<td>
- <tt>@constructor</tt>
+ <code>@dict Description</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
- * A rectangle.
* @constructor
+ * @dict
*/
- function GM_Rect() {
- ...
+ function Foo(x) {
+ this['x'] = x;
}
+ var obj = new Foo(123);
+ var num = obj.x; // warning
+
+ (/** @dict */ { x: 1 }).x = 123; // warning
</CODE_SNIPPET>
</td>
<td>
- Used in a class's documentation to indicate the constructor.
+ When a constructor (<code>Foo</code> in the example) is
+ annotated with <code>@dict</code>, you can only use the
+ bracket notation to access the properties of <code>Foo</code>
+ objects.
+ The annotation can also be used directly on object literals.
</td>
- <td>
- Yes. If omitted the compiler will prohibit instantiation.
- </td>
</tr>
<tr>
- <td><a name="tag-interface">@interface</a></td>
+ <td><a name="tag-enum">@enum</a></td>
<td>
- <tt>@interface</tt>
+ <code>@enum {Type}</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
- * A shape.
- * @interface
+ * Enum for tri-state values.
+ * @enum {number}
*/
- function Shape() {};
- Shape.prototype.draw = function() {};
+ project.TriState = {
+ TRUE: 1,
+ FALSE: -1,
+ MAYBE: 0
+ };
+ </CODE_SNIPPET>
+ </td>
+ </tr>
- /**
- * A polygon.
- * @interface
- * @extends {Shape}
- */
- function Polygon() {};
- Polygon.prototype.getSides = function() {};
+ <tr>
+ <td><a name="tag-export">@export</a></td>
+ <td>
+ <code>@export</code>
+ <p><i>For example:</i></p>
+ <CODE_SNIPPET>
+ /** @export */
+ foo.MyPublicClass.prototype.myPublicMethod = function() {
+ // ...
+ };
</CODE_SNIPPET>
</td>
- <td>Used to indicate that the function defines an inteface.</td>
<td>
- Yes. The compiler will warn about instantiating an interface.
+ <p>Given the code on the left, when the compiler is run with
+ the <code>--generate_exports</code> flag, it will generate the
+ code:</p>
+ <CODE_SNIPPET>
+ goog.exportSymbol('foo.MyPublicClass.prototype.myPublicMethod',
+ foo.MyPublicClass.prototype.myPublicMethod);
+ </CODE_SNIPPET>
+ <p>which will export the symbols to uncompiled code.
+ Code that uses the <code>@export</code> annotation must either</p>
+ <ol>
+ <li>include <code>//javascript/closure/base.js</code>, or</li>
+ <li>define both <code>goog.exportSymbol</code> and
+ <code>goog.exportProperty</code> with the same method
+ signature in their own codebase.</li>
+ </ol>
</td>
</tr>
<tr>
- <td><a name="tag-type">@type</a></td>
+ <td><a name="tag-expose">@expose</a></td>
<td>
- <tt>
- @type Type<br/>
- @type {Type}
- </tt>
+ <code>@expose</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
- /**
- * The message hex ID.
- * @type {string}
- */
- var hexId = hexId;
+ /** @expose */
+ MyClass.prototype.exposedProperty = 3;
</CODE_SNIPPET>
</td>
<td>
- Identifies the type of a variable, property, or expression.
- Curly braces are not required around most types, but some
- projects mandate them for all types, for consistency.
+ <p>
+ Declares an exposed property. Exposed properties
+ will not be removed, or renamed, or collapsed,
+ or optimized in any way by the compiler. No properties
+ with the same name will be able to be optimized either.
+ </p>
+
+ <p>
+ <code>@expose</code> should never be used in library code,
+ because it will prevent that property from ever getting
+ removed.
+ </p>
</td>
- <td>Yes</td>
</tr>
<tr>
<td><a name="tag-extends">@extends</a></td>
<td>
- <tt>
+ <code>
@extends Type<br/>
@extends {Type}
- </tt>
+ </code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
@@ -2279,19 +2705,60 @@
</CODE_SNIPPET>
</td>
<td>
- Used with @constructor to indicate that a class inherits from
- another class. Curly braces around the type are optional.
+ Used with <code>@constructor</code> to indicate that a class
+ inherits from another class. Curly braces around the type are
+ optional.
</td>
- <td>Yes</td>
</tr>
<tr>
+ <td><a name="tag-externs">@externs</a></td>
+ <td>
+ <code>@externs</code>
+ <p><i>For example:</i></p>
+ <CODE_SNIPPET>
+ /**
+ * @fileoverview This is an externs file.
+ * @externs
+ */
+
+ var document;
+ </CODE_SNIPPET>
+ </td>
+ <td>
+ <p>
+ Declares an
+
+ externs file.
+ </p>
+
+
+ </td>
+ </tr>
+
+ <tr>
+ <td><a name="tag-fileoverview">@fileoverview</a></td>
+ <td>
+ <code>@fileoverview Description</code>
+ <p><i>For example:</i></p>
+ <CODE_SNIPPET>
+ /**
+ * @fileoverview Utilities for doing things that require this very long
+ * but not indented comment.
+ * @author kuth@google.com (Uthur Pendragon)
+ */
+ </CODE_SNIPPET>
+ </td>
+ <td>Makes the comment block provide file level information.</td>
+ </tr>
+
+ <tr>
<td><a name="tag-implements">@implements</a></td>
<td>
- <tt>
+ <code>
@implements Type<br/>
@implements {Type}
- </tt>
+ </code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
@@ -2312,20 +2779,67 @@
</CODE_SNIPPET>
</td>
<td>
- Used with @constructor to indicate that a class implements an
- interface. Curly braces around the type are optional.
+ Used with <code>@constructor</code> to indicate that a class
+ implements an interface. Curly braces around the type are
+ optional.
</td>
+ </tr>
+
+ <tr>
+ <td><a name="tag-inheritDoc">@inheritDoc</a></td>
<td>
- Yes. The compiler will warn about incomplete implementations
- of interfaces.
+ <code>@inheritDoc</code>
+ <p><i>For example:</i></p>
+ <CODE_SNIPPET>
+ /** @inheritDoc */
+ project.SubClass.prototype.toString() {
+ // ...
+ };
+ </CODE_SNIPPET>
</td>
+ <td>
+ <p style="font-weight:bold">Deprecated. Use
+ <code>@override</code> instead.</p>
+
+ Indicates that a method or property of a subclass
+ intentionally hides a method or property of the superclass,
+ and has exactly the same documentation. Notice that
+ <code>@inheritDoc</code> implies <code>@override</code>
+ </td>
</tr>
<tr>
+ <td><a name="tag-interface">@interface</a></td>
+ <td>
+ <code>@interface</code>
+ <p><i>For example:</i></p>
+ <CODE_SNIPPET>
+ /**
+ * A shape.
+ * @interface
+ */
+ function Shape() {};
+ Shape.prototype.draw = function() {};
+
+ /**
+ * A polygon.
+ * @interface
+ * @extends {Shape}
+ */
+ function Polygon() {};
+ Polygon.prototype.getSides = function() {};
+ </CODE_SNIPPET>
+ </td>
+ <td>
+ Used to indicate that the function defines an interface.
+ </td>
+ </tr>
+
+ <tr>
<td><a name="tag-lends">@lends</a></td>
<td>
- <tt>@lends objectName</tt><br/>
- <tt>@lends {objectName}</tt>
+ <code>@lends objectName</code><br/>
+ <code>@lends {objectName}</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
goog.object.extend(
@@ -2343,402 +2857,435 @@
Notice that the name in braces is not a type name like
in other annotations. It's an object name. It names
the object on which the properties are "lent".
- For example, <tt>@type {Foo}</tt> means "an instance of Foo",
- but <tt>@lends {Foo}</tt> means "the constructor Foo".<p/>
+ For example, <code>@type {Foo}</code> means "an instance of Foo",
+ but <code>@lends {Foo}</code> means "the constructor Foo".<p/>
The <a href="http://code.google.com/p/jsdoc-toolkit/wiki/TagLends">
JSDoc Toolkit docs</a> have more information on this
annotation.
</td>
- <td>Yes</td>
</tr>
<tr>
- <td><a name="tag-private">@private</a></td>
+ <td><a name="tag-license">@license</a> or
+ <a name="tag-preserve">@preserve</a></td>
<td>
- <tt>@private</tt>
+ <code>@license Description</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
- * Handlers that are listening to this logger.
- * @type Array.&lt;Function&gt;
- * @private
+ * @preserve Copyright 2009 SomeThirdParty.
+ * Here is the full license text and copyright
+ * notice for this file. Note that the notice can span several
+ * lines and is only terminated by the closing star and slash:
*/
- this.handlers_ = [];
</CODE_SNIPPET>
</td>
<td>
- Used in conjunction with a trailing underscore on the method
- or property name to indicate that the member is
- <a href="#Visibility__private_and_protected_fields_">private</a>.
- Trailing underscores may eventually be deprecated as tools are
- updated to enforce <tt>@private</tt>.
+ Anything marked by <code>@license</code> or
+ <code>@preserve</code> will be retained by the compiler and
+ output at the top of the compiled code for that file. This
+ annotation allows important notices (such as legal licenses or
+ copyright text) to survive compilation unchanged. Line breaks
+ are preserved.
</td>
- <td>Enforced with a flag.</td>
</tr>
+
+
+
+
<tr>
- <td><a name="tag-protected">@protected</a></td>
+ <td><a name="tag-noalias">@noalias</a></td>
<td>
- <tt>@protected</tt>
+ <code>@noalias</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
- /**
- * Sets the component's root element to the given element. Considered
- * protected and final.
- * @param {Element} element Root element for the component.
- * @protected
- */
- goog.ui.Component.prototype.setElementInternal = function(element) {
- // ...
- };
+ /** @noalias */
+ function Range() {}
</CODE_SNIPPET>
</td>
<td>
- Used to indicate that the member or property is
- <a href="#Visibility__private_and_protected_fields_">protected</a>.
- Should be used in conjunction with names with no trailing
- underscore.
+ Used in an externs file to indicate to the compiler that the
+ variable or function should not be aliased as part of the
+ alias externals pass of the compiler.
</td>
- <td>Enforced with a flag.</td>
</tr>
<tr>
- <td><a name="tag-this">@this</a></td>
+ <td><a name="tag-nocompile">@nocompile</a></td>
<td>
- <tt>
- @this Type<br/>
- @this {Type}
- </tt>
+ <code>@nocompile</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
- pinto.chat.RosterWidget.extern('getRosterElement',
- /**
- * Returns the roster widget element.
- * @this pinto.chat.RosterWidget
- * @return {Element}
- */
- function() {
- return this.getWrappedComponent_().getElement();
- });
+ /** @nocompile */
+
+ // JavaScript code
</CODE_SNIPPET>
</td>
<td>
- The type of the object in whose context a particular method is
- called. Required when the <tt>this</tt> keyword is referenced
- from a function that is not a prototype method.
+ Used at the top of a file to tell the compiler to parse this
+ file but not compile it.
+ Code that is not meant for compilation and should be omitted
+ from compilation tests (such as bootstrap code) uses this
+ annotation.
+ Use sparingly.
</td>
- <td>Yes</td>
</tr>
<tr>
- <td><a name="tag-supported">@supported</a></td>
+ <td><a name="tag-nosideeffects">@nosideeffects</a></td>
<td>
- <tt>@supported Description</tt>
+ <code>@nosideeffects</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
- /**
- * @fileoverview Event Manager
- * Provides an abstracted interface to the
- * browsers' event systems.
- * @supported So far tested in IE6 and FF1.5
- */
+ /** @nosideeffects */
+ function noSideEffectsFn1() {
+ // ...
+ }
+
+ /** @nosideeffects */
+ var noSideEffectsFn2 = function() {
+ // ...
+ };
+
+ /** @nosideeffects */
+ a.prototype.noSideEffectsFn3 = function() {
+ // ...
+ };
</CODE_SNIPPET>
</td>
<td>
- Used in a fileoverview to indicate what browsers are supported
- by the file.
+ This annotation can be used as part of function and
+ constructor declarations to indicate that calls to the
+ declared function have no side-effects. This annotation
+ allows the compiler to remove calls to these functions if the
+ return value is not used.
</td>
- <td>Unrelated to type checking.</td></tr>
+ </tr>
<tr>
- <td><a name="tag-enum">@enum</a></td>
+ <td><a name="tag-override">@override</a></td>
<td>
- <tt>@enum {Type}</tt>
+ <code>@override</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
- * Enum for tri-state values.
- * @enum {number}
+ * @return {string} Human-readable representation of project.SubClass.
+ * @override
*/
- project.TriState = {
- TRUE: 1,
- FALSE: -1,
- MAYBE: 0
+ project.SubClass.prototype.toString = function() {
+ // ...
};
</CODE_SNIPPET>
</td>
- <td>Used for documenting enum types.</td>
- <td>Fully supported. If Type is omitted, number assumed.</td>
+ <td>
+ Indicates that a method or property of a subclass
+ intentionally hides a method or property of the superclass. If
+ no other documentation is included, the method or property
+ also inherits documentation from its superclass.
+ </td>
</tr>
<tr>
- <td><a name="tag-deprecated">@deprecated</a></td>
+ <td><a name="tag-param">@param</a></td>
<td>
- <tt>@deprecated Description</tt>
+ <code>@param {Type} varname Description</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
- * Determines whether a node is a field.
- * @return {boolean} True if the contents of
- * the element are editable, but the element
- * itself is not.
- * @deprecated Use isField().
+ * Queries a Baz for items.
+ * @param {number} groupNum Subgroup id to query.
+ * @param {string|number|null} term An itemName,
+ * or itemId, or null to search everything.
*/
- BN_EditUtil.isTopEditableField = function(node) {
+ goog.Baz.prototype.query = function(groupNum, term) {
// ...
};
</CODE_SNIPPET>
</td>
<td>
- Used to tell that a function, method or property should not be
- used any more. Always provide instructions on what callers
- should use instead.
+ Used with method, function and constructor calls to document
+ the arguments of a function.<p/>
+
+ <a href="#JsTypes">Type</a>
+ names must be enclosed in curly braces. If the type
+ is omitted, the compiler will not type-check the parameter.
</td>
- <td>Unrelated to type checking</td>
</tr>
<tr>
- <td><a name="tag-override">@override</a></td>
+ <td><a name="tag-private">@private</a></td>
<td>
- <tt>@override</tt>
+ <code>@private</code><br/>
+ <code>@private {type}</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
- * @return {string} Human-readable representation of project.SubClass.
- * @override
+ * Handlers that are listening to this logger.
+ * @private {!Array.&lt;Function&gt;}
*/
- project.SubClass.prototype.toString() {
- // ...
- };
+ this.handlers_ = [];
</CODE_SNIPPET>
</td>
<td>
- Indicates that a method or property of a subclass
- intentionally hides a method or property of the superclass. If
- no other documentation is included, the method or property
- also inherits documentation from its superclass.
+ Used in conjunction with a trailing underscore on the method
+ or property name to indicate that the member is
+ <a href="#Visibility__private_and_protected_fields_">private</a> and final.
</td>
- <td>Yes</td>
</tr>
<tr>
- <td><a name="tag-inheritDoc">@inheritDoc</a></td>
+ <td><a name="tag-protected">@protected</a></td>
<td>
- <tt>@inheritDoc</tt>
+ <code>@protected</code><br/>
+ <code>@protected {type}</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
- /** @inheritDoc */
- project.SubClass.prototype.toString() {
+ /**
+ * Sets the component's root element to the given element.
+ * @param {Element} element Root element for the component.
+ * @protected
+ */
+ goog.ui.Component.prototype.setElementInternal = function(element) {
// ...
};
</CODE_SNIPPET>
</td>
<td>
- Indicates that a method or property of a subclass
- intentionally hides a method or property of the superclass,
- and has exactly the same documentation. Notice that
- @inheritDoc implies @override.
+ Used to indicate that the member or property is
+ <a href="#Visibility__private_and_protected_fields_">protected</a>.
+ Should be used in conjunction with names with no trailing
+ underscore.
</td>
- <td>Yes</td>
</tr>
<tr>
- <td><a name="tag-code">@code</a></td>
+ <td><a name="tag-public">@public</a></td>
<td>
- <tt>{@code ...}</tt>
+ <code>@public</code><br/>
+ <code>@public {type}</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
- * Moves to the next position in the selection.
- * Throws {@code goog.iter.StopIteration} when it
- * passes the end of the range.
- * @return {Node} The node at the next position.
+ * Whether to cancel the event in internal capture/bubble processing.
+ * @public {boolean}
+ * @suppress {visiblity} Referencing this outside this package is strongly
+ * discouraged.
*/
- goog.dom.RangeIterator.prototype.next = function() {
+ goog.events.Event.prototype.propagationStopped_ = false;
+ </CODE_SNIPPET>
+ </td>
+ <td>
+ Used to indicate that the member or property is public. Variables and
+ properties are public by default, so this annotation is rarely necessary.
+ Should only be used in legacy code that cannot be easily changed to
+ override the visibility of members that were named as private variables.
+ </td>
+ </tr>
+
+ <tr>
+ <td><a name="tag-return">@return</a></td>
+ <td>
+ <code>@return {Type} Description</code>
+ <p><i>For example:</i></p>
+ <CODE_SNIPPET>
+ /**
+ * @return {string} The hex ID of the last item.
+ */
+ goog.Baz.prototype.getLastId = function() {
// ...
+ return id;
};
</CODE_SNIPPET>
</td>
<td>
- Indicates that a term in a JSDoc description is code so it may
- be correctly formatted in generated documentation.
+ Used with method and function calls to document the return
+ type. When writing descriptions for boolean parameters,
+ prefer "Whether the component is visible" to "True if the
+ component is visible, false otherwise". If there is no return
+ value, do not use an <code>@return</code> tag.<p/>
+
+ <a href="#JsTypes">Type</a>
+ names must be enclosed in curly braces. If the type
+ is omitted, the compiler will not type-check the return value.
</td>
- <td>Not applicable.</td>
</tr>
<tr>
- <td><a name="tag-license">@license</a> or
- <a name="tag-preserve">@preserve</a></td>
+ <td><a name="tag-see">@see</a></td>
<td>
- <tt>@license Description</tt>
+ <code>@see Link</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/**
- * @preserve Copyright 2009 SomeThirdParty.
- * Here is the full license text and copyright
- * notice for this file. Note that the notice can span several
- * lines and is only terminated by the closing star and slash:
+ * Adds a single item, recklessly.
+ * @see #addSafely
+ * @see goog.Collect
+ * @see goog.RecklessAdder#add
+ ...
+ </CODE_SNIPPET>
+ </td>
+ <td>Reference a lookup to another class function or method.</td>
+ </tr>
+
+ <tr>
+ <td><a name="tag-struct">@struct</a></td>
+ <td>
+ <code>@struct Description</code>
+ <p><i>For example:</i></p>
+ <CODE_SNIPPET>
+ /**
+ * @constructor
+ * @struct
*/
+ function Foo(x) {
+ this.x = x;
+ }
+ var obj = new Foo(123);
+ var num = obj['x']; // warning
+ obj.y = "asdf"; // warning
+
+ Foo.prototype = /** @struct */ {
+ method1: function() {}
+ };
+ Foo.prototype.method2 = function() {}; // warning
</CODE_SNIPPET>
</td>
<td>
- Anything marked by @license or @preserve will be retained by
- the compiler and output at the top of the compiled code for
- that file. This annotation allows important notices (such as
- legal licenses or copyright text) to survive compilation
- unchanged. Line breaks are preserved.
+ When a constructor (<code>Foo</code> in the example) is
+ annotated with <code>@struct</code>, you can only use the dot
+ notation to access the properties of <code>Foo</code> objects.
+ Also, you cannot add new properties to <code>Foo</code>
+ objects after they have been created.
+ The annotation can also be used directly on object literals.
</td>
- <td>Unrelated to type checking.</td>
</tr>
<tr>
- <td><a name="tag-noalias">@noalias</a></td>
+ <td><a name="tag-supported">@supported</a></td>
<td>
- <tt>@noalias</tt>
+ <code>@supported Description</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
- /** @noalias */
- function Range() {}
+ /**
+ * @fileoverview Event Manager
+ * Provides an abstracted interface to the
+ * browsers' event systems.
+ * @supported So far tested in IE6 and FF1.5
+ */
</CODE_SNIPPET>
</td>
<td>
- Used in an externs file to indicate to the compiler that the
- variable or function should not be aliased as part of the
- alias externals pass of the compiler.
+ Used in a fileoverview to indicate what browsers are supported
+ by the file.
</td>
- <td>Unrelated to type checking.</td>
</tr>
<tr>
- <td><a name="tag-define">@define</a></td>
+ <td><a name="tag-suppress">@suppress</a></td>
<td>
- <tt>@define {Type} description</tt>
+ <code>
+ @suppress {warning1|warning2}
+ </code>
+ <code>
+ @suppress {warning1,warning2}
+ </code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
- /** @define {boolean} */
- var TR_FLAGS_ENABLE_DEBUG = true;
-
- /** @define {boolean} */
- goog.userAgent.ASSUME_IE = false;
+ /**
+ * @suppress {deprecated}
+ */
+ function f() {
+ deprecatedVersionOfF();
+ }
</CODE_SNIPPET>
</td>
<td>
- Indicates a constant that can be overridden by the compiler at
- compile-time. In the example, the compiler flag
- <tt>--define='goog.userAgent.ASSUME_IE=true'</tt>
- could be specified in the BUILD file to indicate that the
- constant <tt>goog.userAgent.ASSUME_IE</tt> should be replaced
- with <tt>true</tt>.
+ Suppresses warnings from tools. Warning categories are
+ separated by <code>|</code> or <code>,</code>.
+
</td>
- <td>Unrelated to type checking.</td>
</tr>
-
-
<tr>
- <td><a name="tag-export">@export</a></td>
+ <td><a name="tag-template">@template</a></td>
<td>
- <tt>@export</tt>
+ <code>@template</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
- /** @export */
- foo.MyPublicClass.prototype.myPublicMethod = function() {
- // ...
+ /**
+ * @param {function(this:T, ...)} fn
+ * @param {T} thisObj
+ * @param {...*} var_args
+ * @template T
+ */
+ goog.bind = function(fn, thisObj, var_args) {
+ ...
};
</CODE_SNIPPET>
</td>
<td>
- <p>Given the code on the left, when the compiler is run with
- the <tt>--generate_exports</tt> flag, it will generate the
- code:</p>
- <CODE_SNIPPET>
- goog.exportSymbol('foo.MyPublicClass.prototype.myPublicMethod',
- foo.MyPublicClass.prototype.myPublicMethod);
- </CODE_SNIPPET>
- <p>which will export the symbols to uncompiled code.
- Code that uses the <tt>@export</tt> annotation must either</p>
- <ol>
- <li>include <tt>//javascript/closure/base.js</tt>, or</li>
- <li>define both <tt>goog.exportSymbol</tt> and
- <tt>goog.exportProperty</tt> with the same method
- signature in their own codebase.</li>
- </ol>
+ This annotation can be used to declare a
+ <a href="#Template_types">template typename</a>.
</td>
- <td>Unrelated to type checking.</td>
</tr>
<tr>
- <td><a name="tag-const">@const</a></td>
+ <td><a name="tag-this">@this</a></td>
<td>
- <tt>@const</tt>
+ <code>
+ @this Type<br/>
+ @this {Type}
+ </code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
- /** @const */ var MY_BEER = 'stout';
-
+ pinto.chat.RosterWidget.extern('getRosterElement',
/**
- * My namespace's favorite kind of beer.
- * @const
- * @type {string}
+ * Returns the roster widget element.
+ * @this pinto.chat.RosterWidget
+ * @return {Element}
*/
- mynamespace.MY_BEER = 'stout';
-
- /** @const */ MyClass.MY_BEER = 'stout';
+ function() {
+ return this.getWrappedComponent_().getElement();
+ });
</CODE_SNIPPET>
</td>
<td>
- <p>Marks a variable as read-only and suitable for inlining.
- Generates warnings if it is rewritten.</p>
- <p>Constants should also be ALL_CAPS, but the annotation
- should help eliminate reliance on the naming convention.
- Although @final is listed at jsdoc.org and is supported as
- equivalent to @const in the compiler, it is discouraged.
- @const is consistent with JS1.5's const keyword. Note that
- changes to properties of const objects are not currently
- prohibited by the compiler (inconsistent with C++ const
- semantics). The type declaration can be omitted if it can be
- clearly inferred. If present, it must be on its own line. An
- additional comment about the variable is optional.</p>
+ The type of the object in whose context a particular method is
+ called. Required when the <code>this</code> keyword is referenced
+ from a function that is not a prototype method.
</td>
- <td>Supported by type checking.</td>
</tr>
<tr>
- <td><a name="tag-nosideeffects">@nosideeffects</a></td>
+ <td><a name="tag-type">@type</a></td>
<td>
- <tt>@nosideeffects</tt>
+ <code>
+ @type Type<br/>
+ @type {Type}
+ </code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
- /** @nosideeffects */
- function noSideEffectsFn1() {
- // ...
- };
-
- /** @nosideeffects */
- var noSideEffectsFn2 = function() {
- // ...
- };
-
- /** @nosideeffects */
- a.prototype.noSideEffectsFn3 = function() {
- // ...
- };
+ /**
+ * The message hex ID.
+ * @type {string}
+ */
+ var hexId = hexId;
</CODE_SNIPPET>
</td>
<td>
- This annotation can be used as part of function and
- constructor declarations to indicate that calls to the
- declared function have no side-effects. This annotation
- allows the compiler to remove calls to these functions if the
- return value is not used.
+ Identifies the <a href="#JsTypes">type</a> of a variable,
+ property, or expression. Curly braces are not required around
+ most types, but some projects mandate them for all types, for
+ consistency.
</td>
- <td>Unrelated to type checking.</td>
</tr>
<tr>
<td><a name="tag-typedef">@typedef</a></td>
<td>
- <tt>@typedef</tt>
+ <code>@typedef</code>
<p><i>For example:</i></p>
<CODE_SNIPPET>
/** @typedef {(string|number)} */
@@ -2752,41 +3299,17 @@
</td>
<td>
This annotation can be used to declare an alias of a more
- complex type.
+ <a href="#Typedefs">complex type</a>.
</td>
- <td>Yes</td>
</tr>
- <tr>
- <td><a name="tag-externs">@externs</a></td>
- <td>
- <tt>@externs</tt>
- <p><i>For example:</i></p>
- <CODE_SNIPPET>
- /**
- * @fileoverview This is an externs file.
- * @externs
- */
-
- var document;
- </CODE_SNIPPET>
- </td>
- <td>
- <p>
- Declares an
-
- externs file.
- </p>
-
-
- </td>
- <td>No</td>
- </tr>
</tbody>
</table>
+
+
<p>
You may also see other types of JSDoc annotations in third-party
code. These annotations appear in the
@@ -2823,83 +3346,51 @@
</ul>
</p>
</SUBSECTION>
+ </BODY>
+ </STYLEPOINT>
- <SUBSECTION title="HTML in JSDoc">
- <p>Like JavaDoc, JSDoc supports many HTML tags, like &lt;code&gt;,
- &lt;pre&gt;, &lt;tt&gt;, &lt;strong&gt;, &lt;ul&gt;, &lt;ol&gt;,
- &lt;li&gt;, &lt;a&gt;, and others.</p>
-
- <p>This means that plaintext formatting is not respected. So, don't
- rely on whitespace to format JSDoc:</p>
-
- <BAD_CODE_SNIPPET>
- /**
- * Computes weight based on three factors:
- * items sent
- * items received
- * last timestamp
- */
- </BAD_CODE_SNIPPET>
-
- <p>It'll come out like this:</p>
-
- <tt>Computes weight based on three factors: items sent items received items received</tt>
-
- <p>Instead, do this:</p>
-
- <CODE_SNIPPET>
- /**
- * Computes weight based on three factors:
- * &lt;ul&gt;
- * &lt;li&gt;items sent
- * &lt;li&gt;items received
- * &lt;li&gt;last timestamp
- * &lt;/ul&gt;
- */
- </CODE_SNIPPET>
-
- <p>Also, don't include HTML or HTML-like tags unless you want them to
- be interpreted as HTML.</p>
-
- <BAD_CODE_SNIPPET>
- /**
- * Changes &lt;b&gt; tags to &lt;span&gt; tags.
- */
- </BAD_CODE_SNIPPET>
-
- <p>It'll come out like this:</p>
-
- <tt>Changes <b> tags to <span> tags.</span></b></tt>
-
- <p>On the other hand, people need to be able to read this in its
- plaintext form too, so don't go overboard with the HTML:</p>
-
- <BAD_CODE_SNIPPET>
- /**
- * Changes &amp;lt;b&amp;gt; tags to &amp;lt;span&amp;gt; tags.
- */
- </BAD_CODE_SNIPPET>
-
- <p>People will know what you're talking about if you leave the
- angle-brackets out, so do this:</p>
-
- <CODE_SNIPPET>
- /**
- * Changes 'b' tags to 'span' tags.
- */
- </CODE_SNIPPET>
- </SUBSECTION>
+ <STYLEPOINT title="Providing Dependencies With goog.provide">
+ <SUMMARY>
+ Only provide top-level symbols.
+ </SUMMARY>
+ <BODY>
+ <p>
+ All members defined on a class should be in the same file. So, only
+ top-level classes should be provided in a file that contains multiple
+ members defined on the same class (e.g. enums, inner classes, etc).
+ </p>
+ <p>Do this:</p>
+ <CODE_SNIPPET>
+ goog.provide('namespace.MyClass');
+ </CODE_SNIPPET>
+ <p>Not this:</p>
+ <BAD_CODE_SNIPPET>
+ goog.provide('namespace.MyClass');
+ goog.provide('namespace.MyClass.Enum');
+ goog.provide('namespace.MyClass.InnerClass');
+ goog.provide('namespace.MyClass.TypeDef');
+ goog.provide('namespace.MyClass.CONSTANT');
+ goog.provide('namespace.MyClass.staticMethod');
+ </BAD_CODE_SNIPPET>
+ <p>
+ Members on namespaces may also be provided:
+ </p>
+ <CODE_SNIPPET>
+ goog.provide('foo.bar');
+ goog.provide('foo.bar.method');
+ goog.provide('foo.bar.CONSTANT');
+ </CODE_SNIPPET>
</BODY>
</STYLEPOINT>
<STYLEPOINT title="Compiling">
- <SUMMARY>Encouraged</SUMMARY>
+ <SUMMARY>Required</SUMMARY>
<BODY>
<p>Use of JS compilers such as the
<a href="http://code.google.com/closure/compiler/">Closure Compiler</a>
- is encouraged.</p>
+ is required for all customer-facing code.</p>
@@ -2977,7 +3468,7 @@
<SUBSECTION title="Conditional (Ternary) Operator (?:)">
<p>Instead of this:</p>
<CODE_SNIPPET>
- if (val != 0) {
+ if (val) {
return foo();
} else {
return bar();
@@ -3057,40 +3548,6 @@
</BAD_CODE_SNIPPET>
</SUBSECTION>
- <SUBSECTION title="Use join() to Build Strings">
- <p>It is common to see this:</p>
- <BAD_CODE_SNIPPET>
- function listHtml(items) {
- var html = '&lt;div class="foo"&gt;';
- for (var i = 0; i &lt; items.length; ++i) {
- if (i &gt; 0) {
- html += ', ';
- }
- html += itemHtml(items[i]);
- }
- html += '&lt;/div&gt;';
- return html;
- }
- </BAD_CODE_SNIPPET>
-
- <p>but this is slow in Internet Explorer, so it is better to do
- this:</p>
- <CODE_SNIPPET>
- function listHtml(items) {
- var html = [];
- for (var i = 0; i &lt; items.length; ++i) {
- html[i] = itemHtml(items[i]);
- }
- return '&lt;div class="foo"&gt;' + html.join(', ') + '&lt;/div&gt;';
- }
- </CODE_SNIPPET>
-
- <p>You can also use an array as a stringbuilder, and convert it into
- a string with <code>myArray.join('')</code>. Note that since
- assigning values to an array is faster than using
- <code>push()</code> you should use assignment where possible.</p>
- </SUBSECTION>
-
<SUBSECTION title="Iterating over Node Lists">
<p>Node lists are often implemented as node iterators with a filter.
This means that getting a property like length is O(n), and
@@ -3155,7 +3612,7 @@
</PARTING_WORDS>
<p align="right">
- Revision 2.11
+ Revision 2.93
</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment