Objective
Good JavaScript writing habits of the advantages of self-evident, today's go to recommend the Dojo JavaScript programming specifications, quite good JavaScript programming style specifications, suggest you can draw on this specification to write Javascript. Thanks for I.feelinglucky's translation.
Order
Any violation to this guide is allowed if it enhances readability.
All the code has to be made easy for others to read.
Quick Read Reference
Core API Please use the following style:
Structure |
Rules |
Comments |
Module |
Lowercase |
Do not use multiple semantics (Never multiple words) |
Class |
Camel |
|
Public method |
Mixed |
Other external calls can also be used with lower_case (), such that the style |
Public variables |
Mixed |
|
Constant |
Camel or upper case |
|
The following are not necessary, but are recommended for use:
Structure |
Rules |
Private method |
Mix, Example:_mixedcase |
Private variable |
Mix, Example:_mixedcase |
Method parameter |
Mix, Example:_mixedcase, Mixedcase |
Native (local) variables |
Mix, Example:_mixedcase, Mixedcase |
Naming conventions
1. Variable names must be lowercase letters.
2. The naming of classes uses camels to name the rules, for example:
Account, EventHandler
3. Constants must be declared in the object (class) or in the front of the enumeration variable. Enumeration variables must be named in real sense, and their members must use camels to name the rules or use uppercase:
Copy Code code as follows:
var nodetypes = {
Element:1,
Document:2
}
4. Abbreviated words cannot use uppercase names as variable names:
Getinnerhtml (), getXml (), XmlDocument
5. The order of the method must be a verb or a verb phrase:
Obj.getsomevalue ()
6. The naming of public classes must be named with a mixed name (mixedcase).
The name of a 7.CSS variable must use its corresponding common class variable.
8. Variable attribute members of a private class must be named with a mixed name (Mixedcase), preceded by an underscore (_). For example:
Copy Code code as follows:
var MyClass = function () {
var _buffer;
this.dosomething = function () {
};
}
9. If the variable is set to private, the underscore must precede it.
this._someprivatevariable = statement;
10. A generic variable must use a type name that is consistent with its name:
Settopic (topic)//Variable topic as topic type of variable
11. All variable names must be in English name.
12. If a variable has a broader scope (large scope), it must use a global variable, which can then be designed as a member of a class. Relatively small scopes or private variables are used to name simple words.
13. If the variable has its implied return value, avoid using a similar method:
GetHandler (); Avoid using Geteventhandler ()
14. Public variables must clearly express their own attributes and avoid ambiguous meanings, such as:
MouseEventHandler
, rather than MSEEVTHDLR.
Please pay attention to this rule again, the advantage of doing so is very obvious. It can express the meaning defined by the expression explicitly. For example:
Dojo.events.mouse.Handler//rather than Dojo.events.mouse.MouseEventHandler
15. Class/constructor can be named with the name of an extension of its base class, so that the name of its base class can be found correctly and quickly:
EventHandler
Uieventhandler
MouseEventHandler
A base class can reduce its name by explicitly describing its properties:
MouseEventHandler as opposed to Mouseuieventhandler.
Special Naming conventions
The term "Get/set" does not connect to a field unless it is defined as a private variable.
The variable name preceded by "is" should be a Boolean value, and the same can be "has", "can" or "should".
The term "compute" as a variable name should be a variable that has already been evaluated.
The term "find" as a variable name should be a variable that has been found complete.
The term "initialize" or "init" as the variable name should be a class or other type of variable that has already been instantiated (initialized).
UI (user interface) control variables should be added to the control type after the name, for example: Leftcombobox, Topscrollpane.
The plural must have its public name convention (original: Plural form must be used to name collections).
The variable name convention with "Num" or "count" is a number (object).
The duplicate variable suggests a variable with the name "I", "J", "K" (and so on).
Supplementary terms must be used, for example: Get/set, Add/remove, Create/destroy, Start/stop, Insert/delete, begin/end, etc.
You can abbreviate the name as much as possible using abbreviations.
A Boolean variable name that avoids ambiguity, for example:
Isnoterror, Isnotfound is illegal.
The error class suggests adding "Exception" or "error" after the variable name.
method if you return a class, you should indicate what is returned on the name, or if it is a procedure, what you have done.
File
Indent use a tab stop with 4 blank characters.
If your editor supports file tags, please add the following line to make our code easier to read:
Vim:ts=4:noet:tw=0:
Foreigners use VIM Editor more, this article can choose to follow.
Code folding must appear to be complete and logical:
Copy Code code as follows:
var someexpression = Expression1
+ Expression2
+ Expression3;
var o = someobject.get (
Expression1,
Expression2,
Expression3
);
Note: The indentation of an expression should be consistent with the variable declaration.
Note: The parameters of the function should be explicitly indented, and the indent rules are consistent with the other blocks.
Variable
- The variable must not be used until the declaration is initialized, even if it is of a NULL type.
- Variables do not produce ambiguity.
- The related set of variables should be placed in the same code block, and the unrelated set of variables should not be placed in the same code block.
- Variables should be kept as little as possible to the minimum life cycle.
- Specification for cyclic/duplicate variables:
- You must use a for loop if you have only a circular control block.
- The loop variable should be initialized before the loop starts, and if a for loop is used, the loop variable is initialized with a for statement.
- The "do ... while" statement is allowed.
- The "break" and "continue" statements are still allowed (but please note).
- Conditional expression
- You should try to avoid complex conditional expressions and use temporary Boolean variables if necessary.
- The nominal case SHOULD is put in the ' if ' part and the exception in the ' Else ' part of the ' if ' statement.
- You should avoid adding blocks to a conditional expression.
- Miscellaneous
- Try to avoid magic numbers (Magic numbers), and they should use constants instead.
- A floating-point variable must indicate one digit (even 0) after the decimal point.
- Floating-point variables must indicate the real part, even if they are 0 (use 0.) Beginning).
Layout
Block
The normal code snippet should look as follows:
Copy Code code as follows:
while (!isdone) {
DoSomething ();
Isdone = Moretodo ();
}
The IF statement should look like this:
Copy Code code as follows:
if (somecondition) {
statements;
else if (someothercondition) {
statements;
} else {
statements;
}
The For statement should look like this:
Copy Code code as follows:
for (initialization; condition update) {
statements;
}
The while statement should look like this:
Copy Code code as follows:
while (!isdone) {
DoSomething ();
Isdone = Moretodo ();
}
Do ... The while statement should look like this:
Copy Code code as follows:
do {
statements;
while (condition);
The SWITCH statement should look like this:
Copy Code code as follows:
Switch (condition) {
Case ABC:
statements;
Fallthrough
Case DEF:
statements;
Break
Default
statements;
Break
}
TRY ... The CATCH statement should look like this:
Copy Code code as follows:
try {
statements;
catch (ex) {
statements;
finally {
statements;
}
The if–else,while or for statement of a single line must also be enclosed in parentheses, but they can write this:
if (condition) {statement;}
while (condition) {statement}
for (intialization; condition update) {statement;}
Blank
- The operator suggests using a space to separate (including ternary operators).
- The following keywords avoid using whitespace:
- Break
- Catch
- Continue
- Todo
- Else
- Finally
- For
- function (If an anonymous function, for example: var foo = function () {}; )
- If
- Return
- Switch
- This
- Try
- void
- While
- With
- The following keywords must be separated by whitespace:
- Case
- Default
- Delete
- function (if declared, for example: function foo () {}; )
- In
- instanceof
- New
- Throw
- typeof
- Var
- The comma (,) is recommended for white space.
- The colon (:) is recommended for white space separation.
- The point (.) is suggested to use a blank space in the latter part.
- Point (.) to avoid using white space in the front.
- function calls and methods avoid using whitespace, for example: DoSomething (Someparameter); Rather than dosomething (Someparameter)
- Use blank lines between logical blocks.
- Declares that alignment is recommended to make it easier to read.
Comments
- Jerky Code is not necessary to add comments, first you need to rewrite them.
- Please use English for all comments.
- From a resolved scenario to an untapped feature, the annotation must be related to the code.
- A large number of variable declarations must follow a comment.
- Comments need to explain the usefulness of the code snippet, especially the code snippet that follows.
- Note It is not necessary to add each row.
Document
Here are some basic functions or description methods for objects:
Summary (Summary): Briefly describe the purpose of this function or object implementation
Description (description): A brief description of this function or class
Return: Describes what this function returns (does not include the return type)
Basic function Information
Copy Code code as follows:
function () {
Summary:soon we'll have enough treasure to the rule all of New Jersey.
Description:or we could just get a new roomate.
Look, your go find him. He don ' t yell in you.
All I ever try to do are make him smile and sing around
Him and dance around him and him just into me.
He told me to get in the freezer ' cause there is a carnival in there.
Returns:look, a Bananarama tape!
}
Object function Information
No return value description
Copy Code code as follows:
{
Summary:dingle, engage the rainbow machine!
Description
Tell you what, I wish I was--oh I g--that beam,
Coming up like that, the speed, your might wanna adjust that.
It really did a number on me back, there. I mean, and I don ' t
Wanna say Whiplash, just yet, cause that ' s a little too,
But, ' re insured, right?
}
Declaration of functions
In some cases, the invocation and declaration of a function are implicitly (invisible). In this case, we have no way to add a description to the function (for program invocation). If you encounter this situation, you can use a class to encapsulate the function.
Note: This method can only be in cases where the function has no initialization parameters. If they are not, they are ignored.
Copy Code code as follows:
Dojo.declare (
"Foo",
Null
{
Summary:phew, this sure is relaxing, Frylock.
Description
Thousands of years ago, before the dawn of
Man as we knew him, there is Sir Santa of Claus:an
Ape-like creature making crude and pointless toys out
of Dino-bones, hurling them at chimp-like creatures with
Crinkled hands regardless of how they behaved the
Previous year.
Returns:unless Carl pays tribute to the elfin elders into space.
}
);
<ol>
<li> Simple Type
A simple type of parameter can be directly annotated in the function parameter definition.
[CC lang= "JavaScript"]function (/*string*/foo,/*int*/bar) ...
Soft type parameters
Here are a few modifiers for reference:
? Optional parameters
... The range of surface parameters is uncertain.
Array
function (/*string?*/foo,/*int ...) * * Bar,/*string[]*/baz) ...
Global parameter description
If you want to add a description, you can move them to the initialization block.
The basic Information format is: * Keyword * Description field (*key* descriptive sentence)
Parameters and variables are formatted as: * keyword * ~* type *~ Description field (*key* ~*type*~ descriptive sentence)
NOTE: * keyword * and ~* type *~ can be expressed using any letter or number.
Copy Code code as follows:
function (foo, bar) {
Foo:string
Used for being the "the" a parameter
Bar:int
Used for being the second parameter
}
Variable
Because the declarations of instance variables, prototype variables, and external variables are consistent, there are many ways to declare and modify variables. How to define and locate information such as the name, type, scope, and so on of the variable where the variable appears first.
Copy Code code as follows:
function foo () {
Mystring:string
Times:int
How many times to print myString
Separator:string
What to print out in between mystring*
this.mystring = "placeholder text";
This.times = 5;
}
foo.prototype.setString = function (myString) {
this.mystring = myString;
}
foo.prototype.toString = function () {
for (int i = 0; i < this.times; i++) {
Dojo.debug (this.mystring);
Dojo.debug (Foo.separator);
}
}
Foo.separator = "=====";
variable annotation in an object
You should use annotations that are consistent with object values and methods, such as when they are declared:
Copy Code code as follows:
{
Key:string
A Simple Value
Key: "Value",
Key2:string
Another Simple Value
}
return value
Because a function can return multiple values of different (types) at the same time, a comment of the return type should be added after each return value. Note within a row, if all the return values are the same type, indicate the type returned and, for multiple different return values, the callout return type is "mixed".
Copy Code code as follows:
function () {
if (arguments.length) {
Return "passed argument (s)"; String
} else {
return false; Boolean
}
}
Pseudo code (pending discussion)
Sometimes you need to add a functional process description for this function or class in a function or class. If you're going to do this, you can use/*======== (= character to appear 5 or more), and the advantage of doing so is that you don't have to add the code (the original author's meaning might be a code management system).
This looks like there will be a very long annotation in/*===== and =====*/, and you can consider whether to delete it after you wait for the function to adjust.
Copy Code code as follows:
/*=====
Module.pseudo.kwArgs = {
Url:string
The location of the file
URL: "",
Mimetype:string
text/html, Text/xml, etc
MimeType: ""
}
=====*/
function (/*module.pseudo.kwargs*/Kwargs) {
Dojo.debug (Kwargs.url);
Dojo.debug (Kwargs.mimetype);
}
Original link: http://dojotoolkit.org/developer/StyleGuide
Translation (translated by): I.feelinglucky{at}gmail.com from http://www.gracecode.com