Any violation to this guide is allowed if it enhances readability.
All code should become readable for others.
The long-term value of software is directly derived from its coding quality. In its entire lifecycle
Program
It may be read or modified by many people. If
Program
It can clearly display its structure and features, which can reduce the possibility of errors when it is modified in the future.
Programming specifications can help
Program
Increased staff
Program
Robustness. All JavaScript code is exposed to the public. Therefore, we should ensure its quality. It is important to keep clean.
JavaScript files
Javascript
Program
Files with the extension. js should be stored independently.
JavaScript code should not be included in HTML files unless it is a specific code segment that only belongs to this part. The javascript code in HTML significantly increases the file size and cannot be cached or compressed.
Filename. js should be placed behind the body as much as possible. This reduces load
Script
Other pages
Content
Load
Latency also occurs. You do not need to use the language or type attribute. The MIME type is server rather than scripttag
. (Good luck: I personally think it is recommended to specify the type attribute according to web standards and put <SCRIPT> to
<Head> medium .)
Indent
The unit of indentation is four spaces. Avoid using the tab key for indentation. Because there is no uniform tab length standard. Although space is used to increase the file size, it can be ignored in the LAN and eliminated during the minimization process.
Length of each line
Avoid exceeding 80 characters in each line. When one statement cannot be written in one row, consider line-by-line statements. It is better to wrap a line after a comma in the operator number. Line feed after the operator can reduce the probability that errors caused by copying and pasting will be overwritten by semicolons.
Note
Do not comment. It is very useful to leave information for people who need to understand your code in the future (maybe yourself. Annotations should be well written and clear like the code they annotate. Occasional humor is even better. Remember to avoid being lengthy or emotional.
It is also important to update annotations in a timely manner. The incorrect comment will make
Program
It is more difficult to read and understand.
Make comments meaningful. The focus is on explaining the logic that is not easy to understand immediately. Do not set the reader's
Time
Waste reading is similar:
I = 0; // make I equal to 0
Use a single line comment. Block annotations are used to annotate formal documents and useless code.
Variable Declaration
All variables must be in use
Forward
Statement. JavaScript does not have to do this, but this can make
Program
It is easy to read and discover undeclared variables (they will be compiled into global variables ).
Place the VaR statement in the header of the function.
It is best to put the declaration statement of each variable into a single row and add comments. All variables are sorted alphabetically.
VaR currententry; // The current selected item.
VaR level; // indent level
VaR size; // table size
Javascript has no block range, so defining variables in the block can easily cause C/C ++/Java
Program
Personnel misunderstanding. Define all variables in the function header.
Minimize the use of global variables. Do not overwrite local variables.
Function Declaration
All functions are in use
Forward
Statement. The internal function declaration follows the VaR statement. This helps you determine which variables are within the function range.
There should be no space between the function name and "(" (left parenthesis. ")" (Right Parenthesis) and start
Program
A space should be inserted between the "{" (left braces) of the body. Function
Program
The body should be indented with four spaces. "}" (Right braces) and the line of the declared function
Docks
.
Function outer (c, d ){
VaR E = C * D;
Function inner (a, B ){
Return (E * A) + B;
}
Return inner (0, 1 );
}
The following writing method can be used normally in Javascript, because in Javascript, the declaration of functions and objects can be placed where any expression permits. And it makes inline functions and hybrid structures have the best readability.
Function getelementsbyclassname (classname ){
VaR Results = [];
Define thedom (document. Body, function (node ){
VaR A; // array of class names
VaR c = node. classname; // The node's classname
VaR I; // loop counter
// If the node has a class name, then split it into a list of simple names.
// If any of them match the requested name, then append the node to the set of results.
If (c ){
A = C. Split ('');
For (I = 0; I <A. length; I + = 1 ){
If (=== Classname ){
Results. Push (node );
Break;
}
}
}
});
Return results;
}
If the function is an anonymous function, there should be a space between the function and "(" (left parenthesis. If spaces are omitted, the function name may be used as a function.
Div. onclick = function (e ){
Return false;
};
That = {
Method: function (){
Return this. datum;
},
Datum: 0
};
Do not use global functions.
Name
The variable name should consist of 26 uppercase and lowercase letters (A. Z, A. Z), 10 digits (0. 9), and "_" (underline. Avoid using international characters (such as Chinese characters) because they are not easily read and understood anywhere. Do not use "$" (dollar sign) or "" (backslash) in the name ).
Do not use underscores (_) as the first character of the variable name. It is sometimes used to indicate private variables, but JavaScript does not actually provide the function of private variables. If private variables are important, they are in the form of private members. Avoid the use of this easy-to-misunderstand naming convention.
Most variable names and method life should start with a lowercase letter.
The name of the constructor that must be used with new must start with an uppercase letter. When new is omitted, JavaScript will not throw any compilation or running errors. If you forget to add new, it will make bad things happen (such as being treated as a common function). Therefore, the only way to avoid such a situation is to use the upper-case constructor name.
All global variables should be capitalized. (JavaScript does not have macros or constants, so it will not cause misunderstanding)
Statement
Simple statement
Each row can contain at most one statement. Place "," (semicolon) at the end of each simple statement. Note that a function value assignment or object Value assignment statement is also a value assignment statement and should end with a semicolon.
Javascript can treat any expression as a statement. This can easily hide some errors, especially the error of incorrect bonus points. The expression should be treated as a separate statement only when values are assigned and called.
Compound statement
A compound statement is a sequence of statements contained in braces (braces.
The enclosed statement must be indented by four spaces.
"{" (Left braces) should end with the actual row of the compound statement.
"}" (Right braces) should be aligned with the beginning of the line of "{" (left braces.
Braces should be used in all compound statements, even if there is only one statement, when they are part of the control structure, such as an if or for statement. In this way, you can avoid errors when you add statements later.
Mark
Statement labels are optional. Only the following statements must be marked: while, do, for, and switch.
Return Statement
Do not use "()" (parentheses) to enclose the return value in a return statement with a return value. If the expression is returned, the expression should be in the same line as the return keyword to avoid incorrect bonus points.
If statement
The IF statement should be in the following format:
If (condition ){
Statements;
}
If (condition ){
Statements;
} Else {
Statements;
}
If (condition ){
Statements;
} Else if (condition ){
Statements;
} Else {
Statements;
}
For statement
The for statement should be in the following format:
For (initialization; condition; update ){
Statements;
}
For (variable in object) if (filter ){
Statements;
}
The first type of loop is used for the array loop with relevant parameters already known.
The second form is applied to objects. The members in the object prototype will be included in the iterator. Using the pre-defined hasownproperty method to distinguish true object members is a good method:
For (variablein object) if (object. hasownproperty (variable )){
Statements;
}
While statement
The while statement should be in the following format:
While (condition ){
Statements;
}
Do statement
The DO statement should be in the following format:
Do {
Statements;
} While (condition );
Unlike other compound statements, do statements always end with a semicolon.
Switch statement
The switch statement should be in the following format:
Switch (expression ){
Case expression:
Statements;
Default:
Statements;
}
Each case is aligned with the switch. This avoids excessive indentation.
Each set of statements (except for default, which should end with break, return, or throw) should not be executed sequentially.
Try statement
The try statement should be in the following format:
Try {
Statements;
} Catch (variable ){
Statements;
}
Try {
Statements;
} Catch (variable ){
Statements;
} Finally {
Statements;
}
Continue statement
Avoid using the continue statement. It easily makes
Program
The logical process is obscure.
With statement
Do not use the with statement.
Blank
Splitting logic-related code blocks with blank lines can improve
Program
Readability. Spaces should be used in the following cases:
The keyword following "(" (left parenthesis) should be separated by a space.
While (true ){
There should be no space between function parameters and "(" (left parenthesis. This helps distinguish between keywords and function calls. All binary operators except "." (points) and "(" (left brackets) and "[" (left square brackets) are separated by spaces.
There should be no space between the unary operator and its operand, unless the operator is a word, such as typeof.
Each control part, such as the ";" (semicolon) in the for statement, must be followed by a space.
Each comma (,) must be followed by a space.
Other suggestions
{} And []
Use {} instead of new object (). Use [] instead of new array ().
An array is used to store data when the member name is a group of ordered numbers. Use an object to save data when the member name is an irregular string or another one.
, (Comma) Operator
Avoid using the comma operator unless in the control section of a specific for statement. (This does not include comma separators used in object definitions, array definitions, VAR statements, and parameter lists .)
Scope
In JavaScript, the block has no domain. Only functions have domains. Do not use blocks unless in a composite statement.
Value assignment expression
Avoid assigning values in the condition section of the IF and while statements.
If (A = B ){
Is it a correct statement? Or
If (A = B ){
Is it true? Avoid this structure that is difficult to judge.
===And! = Operator.
Use = and! = Operator will be relatively better. = And! = The operator forcibly converts the type. In particular, do not use = to compare with the error value (false, null, undefined, "", 0, Nan ).
Confusing plus and minus signs
Be careful when + is followed by + or ++. This form is easy to confuse. Brackets should be inserted for ease of understanding.
Total = subtotal ++ myinput. value;
It is best to write
Total = subtotal + (+ myinput. value );
In this way, ++ will not be mistaken for ++.
Eval is the devil
Eval is the most vulnerable method in JavaScript. Avoid using it.
Eval has an alias. Do not use the function constructor. Do not pass string parameters to setTimeout or setinterval.