The advantages of good JavaScript writing habits are self-evident. Today, bin Go recommends DojoJavascript programming specifications, which are quite good Javascript programming style specifications. We recommend that you use these specifications to compile Javascript. Thank you for your translation of I. feelinglucky.
Preface
The advantages of good JavaScript writing habits are self-evident. Today, bin Go recommends the Dojo Javascript programming specification, which is a good Javascript programming style specification. We recommend that you use this specification to compile Javascript. Thanks to the translation of I. feelinglucky.
Collation
Any violation to this guide is allowed if it enhances readability.
All code should become readable for others.
Quick read reference
Use the following style for core APIs:
Structure |
Rules |
Note |
Module |
Lowercase |
Do not use multiple semantics (Never multiple words) |
Class |
Camels |
|
Public Method |
Hybrid |
Other external calls can also use lower_case (). |
Public Variables |
Hybrid |
|
Constant |
Camels or upper case |
|
Although the following is not necessary, it is recommended to use:
Structure |
Rules |
Private Method |
Hybrid, for example:_ MixedCase |
Private variable |
Hybrid, for example:_ MixedCase |
Method Parameters |
Hybrid, for example:_ MixedCase and mixedCase |
Local variable |
Hybrid, for example:_ MixedCase and mixedCase |
Naming rules
1. The variable name must be a lowercase letter.
2. Use the camel naming rules for class naming, for example:
Account, EventHandler
3. constants must be declared before the object (class) or enumeration variable. The name of the enumerated variable must be meaningful, and its members must use the camel naming rules or use uppercase letters:
The Code is as follows:
Var NodeTypes = {
Element: 1,
DOCUMENT: 2
}
4. For short words, you cannot use uppercase names as variable names:
GetInnerHtml (), getXml (), XmlDocument
5. The method command must be a verb or verb phrase:
Obj. getSomeValue ()
6. Public classes must be named using a mixed name (mixedCase.
7. The same public variables must be used for CSS variable naming.
8. The variable attribute members of the private class must be named using a mixed name (mixedCase) with an underscore (_). For example:
The Code is as follows:
Var MyClass = function (){
Var _ buffer;
This. doSomething = function (){
};
}
9. If the variable is set to private, the prefix must be underlined.
This. _ somePrivateVariable = statement;
10. Common variables must use the same type name as their names:
SetTopic // variable the topic Type Variable
11. All variable names must use English names.
12. If a variable has a wide scope (large scope), the global variable must be used. At this time, it can be designed as a member of a class. If the domain name is relatively small or private, use a concise word name.
13. If a variable has its implicit return value, avoid using similar methods:
GetHandler (); // avoid using getEventHandler ()
14. Public variables must clearly express their own attributes to avoid ambiguity. For example:
MouseEventHandler
Instead of MseEvtHdlr.
Please pay attention to this rule again, and the benefits of doing so are very obvious. It can clearly express the meaning defined by the expression. For example:
Dojo. events. mouse. Handler // instead of dojo. events. mouse. MouseEventHandler
15. The class/constructor can use the extension to name its base class, so that the name of its base class can be found correctly and quickly:
EventHandler
UIEventHandler
MouseEventHandler
The base class can be renamed while its attributes are clearly described:
MouseEventHandler as opposed to MouseUIEventHandler.
Special naming rules
The term "get/set" should not be connected to a field unless it is defined as a private variable.
The variable name with "is" must be a Boolean value. Similarly, it can be "has", "can", or "shocould ".
The term "compute" should be the variable name that has been computed.
The term "find" should be the variable name that has been found.
The term "initialize" or "init" should be a variable of the class or other type that has been instantiated (initialized.
The control variables of the UI (User Interface) should be added with the control type after the name, such as leftComboBox and TopScrollPane.
The Plural value MUST have a common naming convention (Original: Plural form MUST be used to name collections ).
Variable names starting with "num" or "count" are defined as numbers (objects ).
We recommend that you use variable names such as "I", "j", and "k.
Supplementary terms must use supplementary words, such as get/set, add/remove, create/destroy, start/stop, insert/delete, begin/end, etc.
Use abbreviations as much as possible.
Avoid ambiguous Boolean variable names, such:
IsNotError. isNotFound is invalid.
We recommend that you add "Exception" or "Error" to the variable name ".
If a class is returned for the method, the name should indicate what is returned; if a process is returned, it should explain what is done.
File
Use four blank characters for indention.
If your editor supports file tags, add the following line to make our code easier to read:
// Vim: ts = 4: noet: tw = 0:
Note: There are many VIM editors for foreigners. You can choose to follow this article.
Code folding must seem complete and logical:
The Code is as follows:
Var someExpression = Expression1
+ Expression2
+ Expression3;
Var o = someObject. get (
Expression1,
Expression2,
Expression3
);
Note: The indentation of the expression must be consistent with the variable declaration.
Note: The function parameters should adopt explicit indentation, And the indentation Rules should be consistent with other blocks.
Variable
- Variables must be declared and initialized before they can be used, even if they are of the NULL type.
- Variables cannot be ambiguous.
- Related variable sets should be placed in the same code block, and irrelevant variable sets should not be placed in the same code block.
- Keep the minimum life cycle of the variable as much as possible.
- Rules for loop/repeated variables:
- If only the loop control block is used, the FOR loop must be used.
- The loop variable should be initialized before the loop starts. FOR example, if you use the FOR loop, use the FOR statement to initialize the loop variable.
- "Do... The while statement is allowed.
- The "break" and "continue" statements are still allowed (please note ).
- Conditional expressions
- Avoid complex conditional expressions, and use temporary Boolean variables if necessary.
- The nominal case shocould be put in the "if" part and the exception in the "else" part of an "if" statement.
- Avoid adding blocks to conditional expressions.
- Miscellaneous
- Try to avoid Magic numbers, which should be replaced by constants.
- The floating point variable must specify the last digit (even if it is 0) after the decimal point ).
- Floating Point variables must specify the real part, even if they are zero (starting with 0 ).
Layout
Block
The common code segment should look as follows:
The Code is as follows:
While (! IsDone ){
DoSomething ();
IsDone = moreToDo ();
}
The IF statement should look like this:
The Code is as follows:
If (someCondition ){
Statements;
} Else if (someOtherCondition ){
Statements;
} Else {
Statements;
}
The FOR statement should look like this:
The Code is as follows:
For (initialization; condition; update ){
Statements;
}
The WHILE statement should look like this:
The Code is as follows:
While (! IsDone ){
DoSomething ();
IsDone = moreToDo ();
}
DO... The WHILE statement should look like this:
The Code is as follows:
Do {
Statements;
} While (condition );
The SWITCH statement should look like this:
The Code is as follows:
Switch (condition ){
Case ABC:
Statements;
// Fallthrough
Case DEF:
Statements;
Break;
Default:
Statements;
Break;
}
TRY... The CATCH statement should look like this:
The Code is as follows:
Try {
Statements;
} Catch (ex ){
Statements;
} Finally {
Statements;
}
The IF-ELSE, WHILE, or FOR statements of a single row must also be enclosed in parentheses, but they can be written as follows:
If (condition) {statement ;}
While (condition) {statement ;}
For (intialization; condition; update) {statement ;}
Blank
- We recommend that you use spaces to separate operators (including ternary operators ).
- The following keywords should not be separated by spaces:
- Break
- Catch
- Continue
- Do
- Else
- Finally
- For
- Function (if it is an anonymous function, for example: var foo = function (){};)
- If
- Return
- Switch
- This
- Try
- Void
- While
- With
- The following keywords must be separated by spaces:
- Case
- Default
- Delete
- Function (if it is a declaration, for example: function foo (){};)
- In
- Instanceof
- New
- Throw
- Typeof
- Var
- We recommend that you use commas (,) to separate them with spaces.
- We recommend that you use white spaces to separate colons.
- We recommend that you use white spaces to separate points (.) in the back.
- Point (.) To avoid blank spaces in the front.
- Avoid blank space for function calls and methods, such as doSomething (someParameter); // instead of doSomething (someParameter)
- Empty lines are used between logical blocks.
- It is recommended to align the statement to make it easier to read.
Note
- The raw code isNot necessaryAdded comments. First, you needRewriteThey.
- All comments must be in English.
- From the solution to the undeveloped features, commentRequiredCode-related.
- After a large number of variables are declaredRequiredFollow a comment.
- Note the usefulness of the code segment, especially the following code segment.
- NoteNot necessaryAdd each line.
Document
The following describes some basic functions or objects:
Summary: briefly describes the purpose of this function or object implementation.
Description: a brief description of the function or class.
Return: describes what this function returns (excluding the return type)
Basic Function Information
The Code is as follows:
Function (){
// Summary: Soon we will have enough treasure to rule all of New Jersey.
// Description: Or we cocould just get a new roomate.
// Look, you go find him. He don't yell at you.
// All I ever try to do is make him smile and sing around
// Him and dance around him and he just lays into me.
// He told me to get in the freezer 'cause there was a carnival in there.
// Returns: Look, a Bananarama tape!
}
Object Function Information
No return value description
The Code is as follows:
{
// Summary: Dingle, engage the rainbow machine!
// Description:
// Tell you what, I wish I was -- oh my g -- that beam,
// Coming up like that, the speed, you might wanna adjust that.
// It really did a number on my back, there. I mean, and I don't
// Wanna say whiplash, just yet, cause that's a little too far,
// But, you're insured, right?
}
Function Declaration
In some cases, the call and declaration of functions are invisible. In this case, there is no way to add the description in the function (for the program to call ). If this happens, you can use a class to encapsulate functions.
Note: This method can only be used when the function is not initialized. If not, they will be ignored.
The Code is as follows:
Dojo. declare (
"Foo ",
Null,
{
// Summary: Phew, this sure is relaxing, Frylock.
// Description:
// Thousands of years ago, before the dawn
// Man as we knew him, there was Sir Santa of Claus:
// Ape-like creature making crude and pointless toys out
// Of dino-bones, hurling them at chimp-like creatures
// Crinkled hands regardless of how they behaved
// Previous year.
// Returns: Unless Carl pays trigger to the Elfin Elders in space.
}
);
Parameters
- Simple Type
Simple type parameters can be directly annotated in the function parameter definition.
[Cc lang = "javascript"] function (/* String */foo,/* int */bar )...
Variable type parameters
The following are some modifiers for your reference:
? Optional Parameter
... The parameter range of the surface area is unknown.
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.
Basic Information Format: * keyword * Description field (* key * Descriptive sentence)
The format of parameters and variables is: * keyword *~ * Type *~ Description field (* key *~ * Type *~ Descriptive sentence)
Note: * keywords * and ~ * Type *~ It can be expressed in any letter or number. The Code is as follows:
Function (foo, bar ){
// Foo: String
// Used for being the first parameter
// Bar: int
// Used for being the second parameter
}
Variable
Because instance variables, prototype variables, and external variables are declared the same, there are many methods to declare and modify variables. Specifically, how to define and locate the variables should specify the names, types, scopes, and other information of the variables at the first place.
The Code is 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 comment in the object
The annotation method consistent with the object value and method should be used, for example, when they declare:
The Code is as follows:
{
// Key: String
// A simple value
Key: "value ",
// Key2: String
// Another simple value
}
Return Value
Because the function can return multiple different (types) values at the same time, you should add a comment on the return type after each return value. You can annotate within a row. If all returned values are of the same type, the returned type is indicated. If multiple return values are different, the returned type is marked as "mixed ".
The Code is as follows:
Function (){
If (arguments. length ){
Return "You passed argument (s)"; // String
} Else {
Return false; // Boolean
}
}
Pseudocode (to be discussed)
Sometimes you need to add a functional process description for the function or class. If you want to do this, you can use/* = (= it is best to appear five times or more characters ), the advantage of doing so is that you don't need to add these things to the Code (the original author may mean the Code Management System ).
It looks like/* = and = */has a very long comment. After the function is adjusted, you can consider whether to delete it.
The Code is 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 );
}
Link: http://dojotoolkit.org/developer/StyleGuide
Translation (Translated by): I. feelinglucky {at} gmail.com from http://www.gracecode.com