JavaScript code specification

Source: Internet
Author: User
Tags hasownproperty

Translation: cloudwater
Author: Douglas Crockford
Source: http://javascript.crockford.com/code.html

Reprint URL: http://www.yaohaixiao.com /? P = 196

This is a set of encoding specifications applicable to JavaScript programs. It is based on Sun's Java coding specification. But it was significantly modified because JavaScript is not Java.

The long-term value of software is directly derived from its coding quality. Throughout its lifecycle, a program may be read or modified by many people. If a program clearly shows its structure and features, it will reduce the possibility of errors when it is modified later.

Programming specifications can help programmers increase 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 programs should be stored independently in files suffixed with. js.

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> try to put it behind the body. This reduces the latency of loading other page content due to script loading. You do not need to use the language or type attribute. The MIME type is determined by the server rather than the scripttag.

Indent

The unit of indentation is four spaces. Avoid using the Tab key to indent (even though it is already in the 21st Century), there is no unified 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. The next line should be indented with 8 spaces.

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. Incorrect comments make the program 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 waste the reader's time reading something like:

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 declared before use. JavaScript does not have to do this, but it makes it easy for the program 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.

[Code]
Var currentEntry; // The current selected item.
Var level; // indent level
Var size; // table size
[/Code]

JavaScript has no block range, so defining variables in the block can easily lead to misunderstandings of C/C ++/Java programmers. Define all variables in the function header.

Minimize the use of global variables. Do not overwrite local variables.

Function Declaration

All functions are declared before use. 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 .) A space should be inserted between (right brace) and {(left brace) of the Start Program body. The function body should be indented with four spaces. } (Right braces) align with the code header of the line that declares the function.

[Code]
Function outer (c, d ){
Var e = c * d;
Function inner (a, B ){
Return (e * a) + B;
}
Return inner (0, 1 );
}
[/Code]

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.

[Code]
Function getElementsByClassName (className ){
Var results = [];
Define thedom (document. body, function (node ){
Var a; // array of class names
Var c = node. className; // Class Name of the node
Var I; // cyclic 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 (& #39; & #39 ;);
For (I = 0; I <a. length; I + = 1 ){
If (a [I] === className ){
Results. push (node );
Break;
}
}
}
});
Return results;
}
[/Code]

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.

[Code]
Div. onclick = function (e ){
Return false;
};
That = {
Method: function (){
Return this. datum;
},
Datum: 0
};
[/Code]

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 _ (underline) 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. Put; (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.

* 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 {(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 returned 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:

[Code]
If (condition ){
Statements;
}

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

If (condition ){
Statements;
} Else if (condition ){
Statements;
} Else {
Statements;
}
[/Code]

For statement

The for statement should be in the following format:

[Code]
For (initialization; condition; up & #100; ate ){
Statements;
}

For (variable in object) if (filter ){
Statements;
}
[/Code]

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:

[Code]
For (variablein object) if (object. hasOwnProperty (variable )){
Statements;
}
[/Code]

While statement

The while statement should be in the following format:

[Code]
While (condition ){
Statements;
}
[/Code]

Do statement

The do statement should be in the following format:

[Code]
Do {
Statements;
} While (condition );
[/Code]

Unlike other compound statements, do statements always end with; (semicolon.

Switch statement

The switch statement should be in the following format:

[Code]
Switch (expression ){
Case expression:
Statements;
Default:
Statements;
}
[/Code]

Each case is aligned with the switch. This avoids excessive indentation.

Each group of statements (except default should end with break, return, or throw. Do not let it be executed in sequence.

Try statement

The try statement should be in the following format:

[Code]
Try {
Statements;
} Catch (variable ){
Statements;
}

Try {
Statements;
} Catch (variable ){
Statements;
} Finally {
Statements;
}
[/Code]

Continue statement

Avoid using the continue statement. It is easy to obscure the logic process of the program.

With statement

Do not use the with statement.

Blank

Separating logical-related code blocks with blank lines can improve program readability.

Spaces should be used in the following cases:

* The keywords following (left parenthesis) should be separated by a space.

[Code]
While (true ){
[/Code]

* 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 for statement, must be followed by a space after a semicolon.
* Each, (comma), should 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.

[Code]
If (a = B ){
[/Code]

Is it a correct statement? Or

[Code]
If (a = B ){
[/Code]

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.

[Code]
Total = subtotal ++ myInput. value;
[/Code]

It is best to write

[Code]
Total = subtotal + (+ myInput. value );
[/Code]

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.

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.