JavaScript code specification

Source: Internet
Author: User

Original article: Code Conentions for the JavaScript Programming Language

This is a JavaScript Programming Code specification inspired by Sun's documentation Code Conventions for the Java Programming Language.
Because JavaScript is not Java, this specification is greatly changed compared with the Java specification.

Code Quality accounts for a large proportion of software quality. In the software life cycle, a program will be taken over by many people. If a program can express its own structure and features
Modifying it in the near future will reduce the possibility of program crashes.

Code specifications can help reduce program vulnerabilities.

Webjx. Com


All our JavaScript code is directly released to the public, and it should have the quality of release. Webjx. Com

Neatness counts.


Directory:
JavaScript files
Indent
Row width
Note
Variable Declaration
Method Declaration
Name
Statement
-Simple statement
-Compound statement
-Tag
-Return Statement
-If statement
-For statement
-While statement
-Do statement
-Switch statement
-Try statement
-Continue statement
-With statement
Space
Additional suggestions
-{} And []
-Comma Operator
-Block Scope
-Value assignment expression
-= And! = Operator
-Confusing addition and subtraction
-Evil eval

Webjx. Com

 

JavaScript files
JavaScript programs should be stored and released as a. js file.

JavaScript code should not be embedded in HTML files unless the code is unique to a single session. The JavaScript code in HTML greatly increases the page size, and
It is difficult to mitigate through caching and compression.

Webpage tutorial Network

<Script src = filename. js> the closer the tag is to the back of the body, the better. This reduces the latency of other page components caused by script loading. No need to use
The language or type attribute. The MIME type is determined by the server rather than the script tag. Webpage tutorial Network

Indent
The minimum unit of indentation is four spaces. Do not use the tab key, because (as of this writing in the 21st Century) there still is not a standard
For the placement of tabstops. Using spaces will cause the file to become larger, but this size is irrelevant to the LAN and the difference is eliminated by minification.

Row width
Do not allow a line of code to exceed 80 characters. When a statement cannot be written in a single line, it may be necessary to split it. Split after the operator, preferably after a comma.
Splitting after the operator reduces the possibility of copying-paste errors by inserting a semicolon. The next line should be indented with 8 spaces.

 

Note
Write comments generously. It is useful to leave some information for people who need to understand what you have done (maybe yourself. Annotations should be well written and clear, just like they
The labeled code is the same. Occasionally, it's okay to be humorous. Don't write down frustration and resentment.

It is very important to update annotations. Incorrect comments make the program more difficult to understand and understand.

Webpage tutorial Network


Make comments meaningful. Focus more on things that cannot be immediately visible. Do not use the following content to waste the reader's time:
I = 0; // Set I to zero. Webjx. Com

Line comments are generally used. Use block comments for official documents or external comments.


Variable Declaration
All variables should be declared before use. JavaScript does not force this, but this will make the program easier to read, and it will make the probe undeclared possible to become an implicit globals
Variable is easier.

Webpage tutorial Network

The var statement should be the first statement in the method body. Webjx. Com

Each variable declaration should take one row and have comments. They should be alphabetically arranged.
Var currentEntry; // currentyly selected table entry
Var level; // indentation level
Var size; // size of table Webjx. Com

JavaScript has no block scope, so defining variables in a block may confuse programmers with other C-language experiences. Define all variables at the top of the method.

Use as few global variables as possible. Implicit global variables should never be used.

Method Declaration
All methods should be declared before they are used. The internal method should be behind the var statement. This makes it clearer which variables are included in its scope.


There should be no space between method name and parameter list '(left parentheses. There is a space between ")" (right parentheses) and "{" (left braces.
The method body is Indented by four spaces. '}' (Right braces) should be aligned with the method declaration.
Function outer (c, d ){
Var e = c * d; Webjx. Com

Function inner (a, B ){
Return (e * a) + B;
}

 

Return inner (0, 1 );
}

This specification can work well with JavaScript, because in JavaScript, methods and object literally can be placed anywhere in the allowed expression. It uses internal methods and complexity
Structure provides 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 (a [I] === className ){
Results. push (node );
Break;
}
}
}
});
Return results;
}

If a method is literally anonymous, there should be a space between "function" and "(" (left parentheses. If spaces are omitted, it may look like the method name is
"Function", which is incorrect.
Div. onclick = function (e ){
Return false;
};
That = {
Method: function (){
Return this. datum;
},
Datum: 0;
};

 

Use as few global methods as possible. Webjx. Com

Name
The name should consist of 26 uppercase and lowercase letters (A. Z, a. z), 10 digits (0. 9), and _ (underline. Do not use international characters, because they may not be easy to read or
It is easy to understand anywhere. Do not use $ or \ in the name ).

 

Do not use _ (underline) as the first letter of the name. It is sometimes used to indicate private, but it does not actually provide private.
If private is important, use private members that provides private attributes.
Avoid conventions that demonstrate a lack of competence.

Most variables and method names should start with lowercase letters.

 

Constructors with the new prefix must start with uppercase letters. JavaScript does not report a compile-time warning or runtime warning when new is omitted.
When new is not used, bad events may occur. Therefore, the capitalized initial specification is the only defense we have.

The global variables should all use uppercase letters. (JavaScript has no macros or constants, so it does not require many uppercase letters to indicate JavaScript features .)

Statement

 

Simple statement
Each line should contain at least one statement. Add a semicolon (;) at the end of each simple statement ). Note that a value assignment statement is still
A value assignment statement. Therefore, it must end with a semicolon.


JavaScript allows any expression to be used as a statement. This may cause some errors, especially when a semicolon is inserted. The only expressions that can be used as statements are the value assignment expression and
Call expression. Webpage tutorial Network

Compound statement
A compound statement is a statement that contains a list of statements surrounded by braces (braces.
1. the enclosed statement should be indented with four spaces.
2. "{" (left braces) should be at the end of the row that begins the compound statement.
3. "}" (right braces) should start a new row and align it with the starting position of the matched "{" Row
4. When a statement is part of a control structure, all statements should be surrounded by parentheses, even single-line statements, such as if or for statements. This makes adding statements easier and does not cause brother eight.

Tag
Statement labels are optional. Only the following statements need to be identified by tags: while, do, for, and switch. Webpage tutorial Network

Return Statement
The return statement with a value should not use the "()" (parentheses) to enclose the value. The return value expression must be in the same line as the return keyword to avoid the insertion of semicolons.

 

If statement
The if statement should use the following format:
If (condition ){
Statements;
}

Webjx. Com


If (condition ){
Statements;
} Else {
Statements;
} Webpage teaching network

If (condition ){
Statements;
} Else if (condition ){
Statements;
} Else {
Statements;
}

Webjx. Com

 

For statement
The for statement should use the following format:
For (initialization; condition; update ){
Statements;
} Webpage teaching network

For (variable in object ){
Statements;
}

The first format should be used with arrays.

 

The second format should be used with the object. Note that the members added to the prototype of the object will be included in the traversal. Use the hasOwnProperty method to differentiate objects
Members are wise:
For (variable in object ){
If (object. hasOwnProperty ()){
Statements;
}
}

Webjx. Com


While statement
The while statement should be in the following format:
While (condition ){
Statements;
}

 

Do statement
The do statement should use the following format:
Do {
Statements;
} While (condition );

Webjx. Com

Unlike other compound statements, do statements always end with a semicolon. Webjx. Com

Switch statement
The switch statement should have the following format:
Switch (e-xpression ){
Case e-xpression:
Statements;
Default:
Statements;
}

 

Each case is aligned with the switch, which avoids over-indent. Webjx. Com

Each group of statements (except default) should end with break, return, or throw. Do not use fall through.

Webjx. Com

Try statement
The try statement should use the following format:
Try {
Statements;
} Catch (variable ){
Statements;
}

Webpage tutorial Network

Try {
Statements;
} Catch (variable ){
Statements;
} Finally {
Statements;
} Webjx. Com


Continue statement
Do not use the continue statement. It will blur the control process of the method.

 

With statement
Do not use the with statement.

 

Space
Empty lines increase readability by putting logic-related code together.

 

Spaces should be used in the following scenarios:
1. When the keyword is followed by "(" (left parentheses), it should be separated by a space.
While (true ){

2. Do not have spaces between the method name and the method's ("(left parentheses. This helps distinguish between keywords and method calls.
3. All binary operators except ". "(DOT)," ("(left parentheses), and" ["(left braces) should be separated by a space.
4. The unary operator and the operand should not be separated by spaces, except when the operator is a word, such as typeof.
5. Each ";" (semicolon) in the for statement Control Section should be followed by a space.
6. Each comma (,) should be followed by a space.

Additional suggestions

{} And []
Replace new Object () (). Use [] instead of new Array ().
Use an array when the member name is a continuous integer. Use an object when the member name is any string or name. Webpage tutorial Network

Comma Operator
Do not use the comma operator, except for the strict use of the for statement Control Section. (This is not suitable for the comma operator. It should be used for object literal, array literal, var statement and parameters.
List .)

 

Block Scope
In JavaScript, the block has no scope, and only the method has a scope. Do not use blocks, except for compound statements. Webjx. Com

Value assignment expression
Do not assign values in the condition section of the if and while statements. Do not write obscure code.

Webjx. Com


===And! = Operator
Always use = and! = The operator is better. = And! = The operator performs type forced conversion. In particular, do not use = to compare with "false" values. Webjx. Com

Confusing addition and subtraction
Do not follow "+" or "++" after "+ ". This mode is confusing. Insert parentheses between them to make your intentions clearer.
Total = subtotal ++ myInput. value;

// Is better written

 

Total = subtotal + (+ myInput. value );

In this way, "++" will not be read into "++ ".

Webjx. Com

Evil eval
The eval method is the most abusive feature in JavaScript. Do not use it.
Eval has an alias. Do not use Function constructor. Do not pass a string to setTimeout or setInterval.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.