Hướng dẫn google javascript style guide中文
1 IntroductionThis document serves as the complete definition of Google’s coding standards for source code in the JavaScript programming language. A JavaScript source file is described as being in Google Style if and only if it adheres to the rules herein. Show
Like other programming style guides, the issues covered span not only aesthetic issues of formatting, but other types of conventions or coding standards as well. However, this document focuses primarily on the hard-and-fast rules that we follow universally, and avoids giving advice that isn't clearly enforceable (whether by human or tool). 1.1 Terminology notesIn this document, unless otherwise clarified:
Other terminology notes will appear occasionally throughout the document. 1.2 Guide notesExample code in this document is non-normative. That is, while the examples are in Google Style, they may not illustrate the only stylish way to represent the code. Optional formatting choices made in examples must not be enforced as rules. 2 Source file basics2.1 File nameFile
names must be all lowercase and may include underscores ( 2.2 File encoding: UTF-8Source files are encoded in UTF-8. 2.3 Special characters2.3.1 Whitespace charactersAside from the line terminator sequence, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file. This implies that
2.3.2 Special escape sequencesFor any character that has a special escape sequence ( 2.3.3 Non-ASCII charactersFor the remaining non-ASCII characters, either the actual Unicode character (e.g. Tip: In the Unicode escape case, and occasionally even when actual Unicode characters are used, an explanatory comment can be very helpful.
Tip: Never make your code less readable simply out of fear that some programs might not handle non-ASCII characters properly. If that happens, those programs are broken and they must be fixed. 3 Source file structureAll new source files should either be a
Exactly one blank line separates each section that is present, except the file's implementation, which may be preceded by 1 or 2 blank lines. 3.1 License or copyright information, if presentIf license or copyright information belongs in a file, it belongs here. 3.2 @fileoverview JSDoc, if presentSee ?? for formatting rules. 3.3 goog.module statementAll The entire argument to goog.module is what defines a namespace. It is the package name (an identifier that reflects the fragment of the directory structure where the code lives) plus, optionally, the main class/enum/interface that it defines concatenated to the end. Example
3.3.1 HierarchyModule namespaces may never be named as a direct child of another module's namespace. Disallowed:
The directory hierarchy reflects the namespace hierarchy, so that deeper-nested children are subdirectories of higher-level parent directories. Note that this implies that owners of “parent” namespace groups are necessarily aware of all child namespaces, since they exist in the same directory. 3.3.2 |
Prose form | Correct | Incorrect |
---|---|---|
XML HTTP request | XmlHttpRequest | XMLHTTPRequest |
new customer ID | newCustomerId | newCustomerID |
inner stopwatch | innerStopwatch | innerStopWatch |
supports IPv6 on iOS? | supportsIpv6OnIos | supportsIPv6OnIOS |
YouTube importer | YouTubeImporter | YoutubeImporter* |
*Acceptable, but not recommended.
Note: Some words are ambiguously hyphenated in the English language: for example nonempty and non-empty are both correct, so the method names checkNonempty and checkNonEmpty are likewise both correct.
7 JSDoc
JSDoc is used on all classes, fields, and methods.
7.1 General form
The basic formatting of JSDoc blocks is as seen in this example:
/**
* Multiple lines of JSDoc text are written here,
* wrapped normally.
* @param {number} arg A number to do something to.
*/
function doSomething(arg) { … }
or in this single-line example:
/** @const @private {!Foo} A short bit of JSDoc. */
this.foo_ = foo;
If a single-line comment overflows into multiple lines, it must use the multi-line style with /**
and */
on their own lines.
Many tools extract metadata from JSDoc comments to perform code validation and optimization. As such, these comments must be well-formed.
7.2 Markdown
JSDoc is written in Markdown, though it may include HTML when necessary.
Note that tools that automatically extract JSDoc (e.g. JsDossier) will often ignore plain text formatting, so if you did this:
/**
* Computes weight based on three factors:
* items sent
* items received
* last timestamp
*/
it would come out like this:
Computes weight based on three factors: items sent items received last timestamp
Instead, write a Markdown list:
/**
* Computes weight based on three factors:
*
* - items sent
* - items received
* - last timestamp
*/
7.3 JSDoc tags
Google style allows a subset of JSDoc tags. See ?? for the complete list. Most tags must occupy their own line, with the tag at the beginning of the line.
Disallowed:
/**
* The "param" tag must occupy its own line and may not be combined.
* @param {number} left @param {number} right
*/
function add(left, right) { ... }
Simple tags that do not require any additional data (such as @private
, @const
, @final
, @export
) may be combined onto the same line, along with an optional type when appropriate.
/**
* Place more complex annotations (like "implements" and "template")
* on their own lines. Multiple simple tags (like "export" and "final")
* may be combined in one line.
* @export @final
* @implements {Iterable}
* @template TYPE
*/
class MyClass {
/**
* @param {!ObjType} obj Some object.
* @param {number=} num An optional number.
*/
constructor(obj, num = 42) {
/** @private @const {!Array} */
this.data_ = [obj, num];
}
}
There is no hard rule for when to combine tags, or in which order, but be consistent.
For general information about annotating types in JavaScript see Annotating JavaScript for the Closure Compiler and Types in the Closure Type System.
7.4 Line wrapping
Line-wrapped block tags are indented four spaces. Wrapped description text may be lined up with the description on previous lines, but this horizontal alignment is discouraged.
/**
* Illustrates line wrapping for long param/return descriptions.
* @param {string} foo This is a param with a description too long to fit in
* one line.
* @return {number} This returns something that has a description too long to
* fit in one line.
*/
exports.method = function(foo) {
return 5;
};
Do not indent when wrapping a @desc
or @fileoverview
description.
A file may have a top-level file overview. A copyright notice , author information, and default visibility level 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 may provide a description of the file's contents and any dependencies or compatibility information. Wrapped lines are not indented.
Example:
/**
* @fileoverview Description of file, its uses and information
* about its dependencies.
* @package
*/
Classes, interfaces and records must be documented with a description and any template parameters, implemented interfaces, visibility,
or other appropriate tags. The class description should provide the reader with enough information to know how and when to use the class, as well as any additional considerations necessary to correctly use the class. Textual descriptions may be omitted on the constructor. @constructor
and @extends
annotations are not used with the class
keyword unless the class is being used to declare an @interface
or it extends a generic class.
/**
* A fancier event target that does cool things.
* @implements {Iterable}
*/
class MyFancyTarget extends EventTarget {
/**
* @param {string} arg1 An argument that makes this more interesting.
* @param {!Array} arg2 List of numbers to be processed.
*/
constructor(arg1, arg2) {
// ...
}
};
/**
* Records are also helpful.
* @extends {Iterator}
* @record
* @template TYPE
*/
class Listable {
/** @return {TYPE} The next item in line to be returned. */
next() {}
}
7.7 Enum and typedef comments
All enums and typedefs must be documented with appropriate JSDoc tags (@typedef
or @enum
) on the preceding line. Public enums and typedefs must also have a description. Individual enum items may be documented with a JSDoc comment on the preceding line.
/**
* A useful type union, which is reused often.
* @typedef {!Bandersnatch|!BandersnatchType}
*/
let CoolUnionType;
/**
* Types of bandersnatches.
* @enum {string}
*/
const BandersnatchType = {
/** This kind is really frumious. */
FRUMIOUS: 'frumious',
/** The less-frumious kind. */
MANXOME: 'manxome',
};
Typedefs are useful for defining short record types, or aliases for unions, complex functions, or generic types. Typedefs should be avoided for record types with many fields, since they do not allow
documenting individual fields, nor using templates or recursive references. For large record types, prefer @record
.
7.8 Method and function comments
In methods and named functions, parameter and return types must be documented, except in the case of same-signature @override
s, where all types are omitted. The this
type should be documented when necessary. Return type may be omitted if the function has no non-empty return
statements.
Method, parameter, and return descriptions (but not types) may be omitted if they are obvious from the rest of the method’s JSDoc or from its signature.
Method descriptions begin with a verb phrase that describes what the method does. This phrase is not an imperative sentence, but instead is written in the third person, as if there is an implied This method ... before it.
If a method overrides a superclass method, it must include an @override
annotation. Overridden methods
inherit all JSDoc annotations from the super class method (including visibility annotations) and they should be omitted in the overridden method. However, if any type is refined in type annotations, all @param
and @return
annotations must be specified explicitly.
/** A class that does something. */
class SomeClass extends SomeBaseClass {
/**
* Operates on an instance of MyClass and returns something.
* @param {!MyClass} obj An object that for some reason needs detailed
* explanation that spans multiple lines.
* @param {!OtherClass} obviousOtherClass
* @return {boolean} Whether something occurred.
*/
someMethod(obj, obviousOtherClass) { ... }
/** @override */
overriddenMethod(param) { ... }
}
/**
* Demonstrates how top-level functions follow the same rules. This one
* makes an array.
* @param {TYPE} arg
* @return {!Array}
* @template TYPE
*/
function makeArray(arg) { ... }
If you only need to document the param and return types of a function, you may optionally use inline JSDocs in the function's signature. These inline JSDocs specify the return and param types without tags.
function /** string */ foo(/** number */ arg) {...}
If
you need descriptions or tags, use a single JSDoc comment above the method. For example, methods which return values need a @return
tag.
class MyClass {
/**
* @param {number} arg
* @return {string}
*/
bar(arg) {...}
}
// Illegal inline JSDocs.
class MyClass {
/** @return {string} */ foo() {...}
}
/** Function description. */ bar() {...}
In anonymous functions annotations are generally optional. If the automatic type inference is insufficient or explicit annotation improves readability, then annotate param and return types like this:
promise.then(
/** @return {string} */
(/** !Array */ items) => {
doSomethingWith(items);
return items[0];
});
For function type expressions, see ??.
Property types must be documented. The description may be omitted for private properties, if name and type provide enough documentation for understanding the code.
Publicly exported constants are commented the same way as properties.
/** My class. */
class MyClass {
/** @param {string=} someString */
constructor(someString = 'default string') {
/** @private @const {string} */
this.someString_ = someString;
/** @private @const {!OtherType} */
this.someOtherThing_ = functionThatReturnsAThing();
/**
* Maximum number of things per pane.
* @type {number}
*/
this.someProperty = 4;
}
}
/**
* The number of times we'll try before giving up.
* @const {number}
*/
MyClass.RETRY_COUNT = 33;
7.10 Type annotations
Type annotations are found on @param
, @return
, @this
, and @type
tags,
and optionally on @const
, @export
, and any visibility tags. Type annotations attached to JSDoc tags must always be enclosed in braces.
7.10.1 Nullability
The type system defines modifiers !
and ?
for non-null and nullable, respectively. These modifiers must precede the type.
Nullability modifiers have different requirements for different types, which fall into two broad categories:
- Type annotations for primitives (
string
,number
,boolean
,symbol
,undefined
,null
) and literals ({function(...): ...}
and{{foo: string...}}
) are always non-nullable by default. Use the?
modifier to make it nullable, but omit the redundant!
. - Reference types (generally, anything in
UpperCamelCase
, includingsome.namespace.ReferenceType
) refer to a class, enum, record, or typedef defined elsewhere. Since these types may or may not be nullable, it is impossible to tell from the name alone whether it is nullable or not. Always use explicit?
and!
modifiers for these types to prevent ambiguity at use sites.
Bad:
const /** MyObject */ myObject = null; // Non-primitive types must be annotated.
const /** !number */ someNum = 5; // Primitives are non-nullable by default.
const /** number? */ someNullableNum = null; // ? should precede the type.
const /** !{foo: string, bar: number} */ record = ...; // Already non-nullable.
const /** MyTypeDef */ def = ...; // Not sure if MyTypeDef is nullable.
// Not sure if object (nullable), enum (non-nullable, unless otherwise
// specified), or typedef (depends on definition).
const /** SomeCamelCaseName */ n = ...;
Good:
const /** ?MyObject */ myObject = null;
const /** number */ someNum = 5;
const /** ?number */ someNullableNum = null;
const /** {foo: string, bar: number} */ record = ...;
const /** !MyTypeDef */ def = ...;
const /** ?SomeCamelCaseName */ n = ...;
7.10.2 Type Casts
In cases where the compiler doesn't accurately infer the type of an expression, and the assertion functions in goog.asserts cannot remedy it , it is possible to tighten the type by adding a type annotation comment and enclosing the expression in parentheses. Note that the parentheses are required.
/** @type {number} */ (x)
7.10.3 Template Parameter Types
Always specify template parameters. This way compiler can do a better job and it makes it easier for readers to understand what code does.
Bad:
const /** !Object */ users = {};
const /** !Array */ books = [];
const /** !Promise */ response = ...;
Good:
const /** !Object */ users = {};
const /** !Array */ books = [];
const /** !Promise */ response = ...;
const /** !Promise */ thisPromiseReturnsNothingButParameterIsStillUseful = ...;
const /** !Object */ mapOfEverything = {};
Cases when template parameters should not be used:
Object
is used for type hierarchy and not as map-like structure.
7.10.4 Function type expressions
Terminology Note: function type expression refers to a type annotation for function types with the keyword function
in the annotation (see examples below).
Where the function definition is given, do not use a function type expression. Specify parameter and return types with @param
and @return
, or with inline annotations (see
??). This includes anonymous functions and functions defined and assigned to a const (where the function jsdoc appears above the whole assignment expression).
Function type expressions are needed, for example, inside @typedef
, @param
or @return
. Use it also for variables or properties of function type, if they are not immediately initialized with the function definition.
/** @private {function(string): string} */
this.idGenerator_ = googFunctions.identity;
When using a function type expression, always specify the return type explicitly. Otherwise the default return type is unknown (?
), which leads to strange and unexpected behavior, and is rarely what is actually desired.
Bad - type error, but no warning given:
/** @param {function()} generateNumber */
function foo(generateNumber) {
const /** number */ x = generateNumber(); // No compile-time type error here.
}
foo(() => 'clearly not a number');
Good:
/**
* @param {function(): *} inputFunction1 Can return any type.
* @param {function(): undefined} inputFunction2 Definitely doesn't return
* anything.
* NOTE: the return type of `foo` itself is safely implied to be {undefined}.
*/
function foo(inputFunction1, inputFunction2) {...}
7.10.5 Whitespace
Within a type annotation, a single space or line break is required after each comma or colon. Additional line breaks may be inserted to improve readability or avoid exceeding the column limit. These breaks should be chosen and indented following the applicable guidelines (e.g. ?? and ??). No other whitespace is allowed in type annotations.
Good:
/** @type {function(string): number} */
/** @type {{foo: number, bar: number}} */
/** @type {number|string} */
/** @type {!Object} */
/** @type {function(this: Object, number): string} */
/**
* @type {function(
* !SuperDuperReallyReallyLongTypedefThatForcesTheLineBreak,
* !OtherVeryLongTypedef): string}
*/
/**
* @type {!SuperDuperReallyReallyLongTypedefThatForcesTheLineBreak|
* !OtherVeryLongTypedef}
*/
Bad:
// Only put a space after the colon
/** @type {function(string) : number} */
// Put spaces after colons and commas
/** @type {{foo:number,bar:number}} */
// No space in union types
/** @type {number | string} */
7.11 Visibility annotations
Visibility annotations (@private
, @package
, @protected
) may be specified in a @fileoverview
block, or on any exported symbol or property. Do not specify visibility for local variables, whether within a function or at the top level of a module. All @private
names must end with an underscore.
8 Policies
8.1 Issues unspecified by Google Style: Be Consistent!
For any style question that isn't settled definitively by this specification, prefer to do what the other code in the same file is already doing. If that doesn't resolve the question, consider emulating the other files in the same package.
8.2 Compiler warnings
8.2.1 Use a standard warning set
As far as possible projects should use --warning_level=VERBOSE
.
8.2.2 How to handle a warning
Before doing anything, make sure you understand exactly what the warning is telling you. If you're not positive why a warning is appearing, ask for help .
Once you understand the warning, attempt the following solutions in order:
- First, fix it or work around it. Make a strong attempt to actually address the warning, or find another way to accomplish the task that avoids the situation entirely.
- Otherwise, determine if it's a false
alarm. If you are convinced that the warning is invalid and that the code is actually safe and correct, add a comment to convince the reader of this fact and apply the
@suppress
annotation. - Otherwise, leave a TODO comment. This is a last resort. If you do this, do not suppress the warning. The warning should be visible until it can be taken care of properly.
8.2.3 Suppress a warning at the narrowest reasonable scope
Warnings are suppressed at the narrowest reasonable scope, usually that of a single local variable or very small method. Often a variable or method is extracted for that reason alone.
Example
/** @suppress {uselessCode} Unrecognized 'use asm' declaration */
function fn() {
'use asm';
return 0;
}
Even a large number of suppressions in a class is still better than blinding the entire class to this type of warning.
8.3 Deprecation
Mark deprecated methods, classes or interfaces with @deprecated
annotations. A deprecation comment must include simple, clear directions for people to fix their call sites.
8.4 Code not in Google Style
You will occasionally encounter files in your codebase that are not in proper Google Style. These may have come from an acquisition, or may have been written before Google Style took a position on some issue, or may be in non-Google Style for any other reason.
8.4.1 Reformatting existing code
When updating the style of existing code, follow these guidelines.
- It is not required to change all existing code to meet current style guidelines. Reformatting existing code is a trade-off between code churn and consistency. Style rules evolve over time and these kinds of tweaks to maintain compliance would create unnecessary churn. However, if significant changes are being made to a file it is expected that the file will be in Google Style.
- Be careful not to allow opportunistic style fixes to muddle the focus of a CL. If you find yourself making a lot of style changes that aren’t critical to the central focus of a CL, promote those changes to a separate CL.
8.4.2 Newly added code: use Google Style
Brand new files use Google Style, regardless of the style choices of other files in the same package.
When adding new code to a file that is not in Google Style, reformatting the existing code first is recommended, subject to the advice in ??.
If this reformatting is not done, then new code should be as consistent as possible with existing code in the same file, but must not violate the style guide.
8.5 Local style rules
Teams and projects may adopt additional style rules beyond those in this document, but must accept that cleanup changes may not abide by these additional rules, and must not block such cleanup changes due to violating any additional rules. Beware of excessive rules which serve no purpose. The style guide does not seek to define style in every possible scenario and neither should you.
8.6 Generated code: mostly exempt
Source code generated by the build process is not required to be in Google Style. However, any generated identifiers that will be referenced from hand-written source code must follow the naming requirements. As a special exception, such identifiers are allowed to contain underscores, which may help to avoid conflicts with hand-written identifiers.
9 Appendices
9.1 JSDoc tag reference
JSDoc serves multiple purposes in JavaScript. In addition to being used to generate documentation it is also used to control tooling. The best known are the Closure Compiler type annotations.
9.1.1 Type annotations and other Closure Compiler annotations
Documentation for JSDoc used by the Closure Compiler is described in Annotating JavaScript for the Closure Compiler and Types in the Closure Type System.
9.1.2 Documentation annotations
In addition to the JSDoc described in Annotating JavaScript for the Closure Compiler the following tags are common and well supported by various documentation generation tools (such as JsDossier) for purely documentation purposes.
You may also see other types of JSDoc annotations in third-party code. These annotations appear in the JSDoc Toolkit Tag Reference but are not considered part of valid Google style.
9.1.2.1 @author
or @owner
-
Not recommended.
Not recommended.
Syntax: @author (First Last)
/**
* @fileoverview Utilities for handling textareas.
* @author (Uthur Pendragon)
*/
Documents the author of a file or the owner of a test, generally only used in the @fileoverview
comment. The @owner
tag is used by the unit test dashboard to determine who owns the test results.
9.1.2.2 @bug
Syntax: @bug bugnumber
/** @bug 1234567 */
function testSomething() {
// …
}
/**
* @bug 1234568
* @bug 1234569
*/
function testTwoBugs() {
// …
}
Indicates what bugs the given test function regression tests.
Multiple bugs should each have their own @bug
line,
to make searching for regression tests as easy as possible.
9.1.2.3 @code
- Deprecated. Do not use.
Deprecated. Do not use. Use Markdown backticks instead.
Syntax: {@code ...}
Historically, `BatchItem`
was written as {@code BatchItem}
.
/** Processes pending `BatchItem` instances. */
function processBatchItems() {}
Indicates that a term in a JSDoc description is code so it may be correctly formatted in generated documentation.
9.1.2.4 @desc
Syntax: @desc Message description
/** @desc Notifying a user that their account has been created. */
exports.MSG_ACCOUNT_CREATED = goog.getMsg(
'Your account has been successfully created.');
9.1.2.5 @link
Syntax: {@link ...}
This tag is used to generate cross-reference links within generated documentation.
/** Processes pending {@link BatchItem} instances. */
function processBatchItems() {}
Historical note: @link tags have also been used to create external links in generated documentation. For external links, always use Markdown's link syntax instead:
/**
* This class implements a useful subset of the
* [native Event interface](https://dom.spec.whatwg.org/#event).
*/
class ApplicationEvent {}
9.1.2.6 @see
Syntax: @see Link
/**
* Adds a single item, recklessly.
* @see #addSafely
* @see goog.Collect
* @see goog.RecklessAdder#add
*/
Reference a lookup to another class function or method.
9.1.2.7 @supported
Syntax: @supported Description
/**
* @fileoverview Event Manager
* Provides an abstracted interface to the browsers' event systems.
* @supported IE10+, Chrome, Safari
*/
Used in a fileoverview to indicate what browsers are supported by the file.
9.1.3 Framework specific annotations
The following annotations are specific to a particular framework.
9.1.3.1 @ngInject
for Angular 1
9.1.3.2 @polymerBehavior
for Polymer
https://github.com/google/closure-compiler/wiki/Polymer-Pass
9.1.4 Notes about standard Closure Compiler annotations
The following tags used to be standard but are now deprecated.
9.1.4.1 @expose
- Deprecated. Do not use.
Deprecated. Do not use. Use @export
and/or @nocollapse
instead.
9.1.4.2 @inheritDoc
- Deprecated. Do not use.
Deprecated. Do not use. Use @override
instead.
9.2 Commonly misunderstood style rules
Here is a collection of lesser-known or commonly misunderstood facts about Google Style for JavaScript. (The following are true statements; this is not a list of myths.)
- Neither a copyright statement
nor
@author
credit is required in a source file. (Neither is explicitly recommended, either.) - There is no hard and fast rule governing how to order the members of a class (??).
- Empty blocks can usually be represented concisely as
{}
, as detailed in (??). - The prime directive of line-wrapping is: prefer to break at a higher syntactic level (??).
- Non-ASCII characters are allowed in string literals, comments and JSDoc, and in fact are recommended when they make the code easier to read than the equivalent Unicode escape would (??).
The following tools exist to support various aspects of Google Style.
9.3.1 Closure Compiler
This program performs type checking and other checks, optimizations and other transformations (such as ECMAScript 6 to ECMAScript 5 code lowering).
9.3.2 clang-format
This program reformats JavaScript source code into Google Style, and also follows a number of non-required but frequently readability-enhancing
formatting practices. The output produced by clang-format
is compliant with the style guide.
clang-format
is not required. Authors are allowed to change its output, and reviewers are allowed to ask for such changes; disputes are worked out in the usual way. However, subtrees may choose to opt in to such enforcement locally.
9.3.3 Closure compiler linter
This program checks for a variety of missteps and anti-patterns.
9.3.4 Conformance framework
The JS Conformance Framework is a tool that is part of the Closure Compiler that provides developers a simple means to specify a set of additional checks to be run against their code base above the standard checks. Conformance checks can, for example, forbid access to a certain property, or calls to a certain function, or missing type information (unknowns).
These rules are commonly used to enforce critical
restrictions (such as defining globals, which could break the codebase) and security patterns (such as using eval
or assigning to innerHTML
), or more loosely to improve code quality.
For additional information see the official documentation for the JS Conformance Framework.
9.4 Exceptions for legacy platforms
9.4.1 Overview
This section describes exceptions and additional rules to be followed when modern ECMAScript 6 syntax is not available to the code authors. Exceptions to the recommended style are required when ECMAScript 6 syntax is not possible and are outlined here:
- Use of
var
declarations is allowed - Use of
arguments
is allowed - Optional parameters without default values are allowed
9.4.2 Use var
9.4.2.1 var
declarations are NOT block-scoped
var
declarations are scoped to the beginning of the nearest enclosing function, script or module, which can cause unexpected behavior, especially with function closures that reference var
declarations inside of loops. The following code gives an example:
for (var i = 0; i < 3; ++i) {
var iteration = i;
setTimeout(function() { console.log(iteration); }, i*1000);
}
// logs 2, 2, 2 -- NOT 0, 1, 2
// because `iteration` is function-scoped, not local to the loop.
9.4.2.2 Declare variables as close as possible to first use
Even though var
declarations are scoped to the beginning of the enclosing function, var
declarations should be as close as possible to their first use, for readability purposes. However, do not put a var
declaration inside a block if that variable is referenced outside the block. For example:
function sillyFunction() {
var count = 0;
for (var x in y) {
// "count" could be declared here, but don't do that.
count++;
}
console.log(count + ' items in y');
}
9.4.2.3 Use @const for constants variables
For global declarations
where the const
keyword would be used, if it were available, annotate the var
declaration with @const instead (this is optional for local variables).
9.4.3 Do not use block scoped functions declarations
Do not do this:
if (x) {
function foo() {}
}
While most JavaScript VMs implemented before ECMAScript 6 support function declarations within blocks it was not standardized. Implementations were inconsistent with each other and with the now-standard ECMAScript 6 behavior for block scoped function declaration. ECMAScript 5 and prior only allow for function declarations in the root statement list of a script or function and explicitly ban them in block scopes in strict mode.
To get consistent behavior, instead use a var
initialized with a function expression to define a function within a block:
if (x) {
var foo = function() {};
}
9.4.4 Dependency management with goog.provide
/goog.require
9.4.4.1 Summary
WARNING: goog.provide
dependency management is deprecated. All new files, even in projects using goog.provide
for older files, should use goog.module
. The following rules are for pre-existing goog.provide
files only.
- Place all
goog.provide
s first,goog.require
s second. Separate provides from requires with an empty line. - Sort the entries alphabetically (uppercase first).
- Don't wrap
goog.provide
andgoog.require
statements. Exceed 80 columns if necessary. - Only provide top-level symbols.
goog.provide
statements should be grouped together and placed first. All goog.require
statements should follow. The two lists should be separated with an empty line.
Similar to import statements in other languages, goog.provide
and goog.require
statements should be written in a single line, even if they
exceed the 80 column line length limit.
The lines should be sorted alphabetically, with uppercase letters coming first:
goog.provide('namespace.MyClass');
goog.provide('namespace.helperFoo');
goog.require('an.extremelyLongNamespace.thatSomeoneThought.wouldBeNice.andNowItIsLonger.Than80Columns');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.classes');
goog.require('goog.dominoes');
All members defined on a class should be in the same file. 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).
Do this:
goog.provide('namespace.MyClass');
Not this:
goog.provide('namespace.MyClass');
goog.provide('namespace.MyClass.CONSTANT');
goog.provide('namespace.MyClass.Enum');
goog.provide('namespace.MyClass.InnerClass');
goog.provide('namespace.MyClass.TypeDef');
goog.provide('namespace.MyClass.staticMethod');
Members on namespaces may also be provided:
goog.provide('foo.bar');
goog.provide('foo.bar.CONSTANT');
goog.provide('foo.bar.method');
9.4.4.2
Aliasing with goog.scope
WARNING: goog.scope
is deprecated. New files should not use goog.scope
even in projects with existing goog.scope
usage.
goog.scope
may be used to shorten references to namespaced symbols in code using goog.provide
/goog.require
dependency management.
Only one goog.scope
invocation may be added per file. Always place it in the global scope.
The opening goog.scope(function() {
invocation must be preceded by exactly one blank line and follow any goog.provide
statements,
goog.require
statements, or top-level comments. The invocation must be closed on the last line in the file. Append // goog.scope
to the closing statement of the scope. Separate the comment from the semicolon by two spaces.
Similar to C++ namespaces, do not indent under goog.scope
declarations. Instead, continue from the 0 column.
Only make aliases for 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):
goog.scope(function() {
var Button = goog.ui.Button;
Button = function() { ... };
...
Names must be the same as the last property of the global that they are aliasing.
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 after 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
9.4.4.3 goog.forwardDeclare
Prefer to use goog.requireType
instead of goog.forwardDeclare
to break circular dependencies between files in the same library. Unlike goog.require
, a goog.requireType
statement is allowed to import a namespace before it is defined.
goog.forwardDeclare
may still be used in legacy code to break circular references spanning across
library boundaries, but newer code should be structured to avoid it.
goog.forwardDeclare
statements must follow the same style rules as goog.require
and goog.requireType
. The entire block of goog.forwardDeclare
, goog.require
and goog.requireType
statements is sorted alphabetically.