JavaScript code specification

Source: Internet
Author: User
Tags comments eval lowercase script tag uppercase letter hasownproperty

Original: Code conentions for the JavaScript programming Language

This is a JavaScript programming code specification that is inspired by Sun's document code conventions for the Java programming language.
This specification has a significant change from the Java specification because JavaScript is not java.

Code quality accounts for a large proportion of software quality. A program can be taken over by many people in the software lifecycle. If a program can express its own structure and characteristics well, then the
Modifying it in the near future will reduce the likelihood of a program crashing.

Code specifications can help reduce the vulnerability of programs.

Webjx.com


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

Neatness counts.


Directory:
JavaScript files
Indent
Ruled
Comments
Variable declaration
Method declaration
Named
Statement
-Simple statement
-Compound statement
-Tags
-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
-an assignment expression
-= = = and!== operators
-confusing addition and subtraction
-The Evil eval

Webjx.com

JavaScript files
JavaScript programs should be stored and published 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 size of the page and
It is difficult to mitigate through caching and compression.

Web Teaching Network

<script src=filename.js> label should be in the body in the position of the better. This reduces the delay in other page components caused by loading the script. No need to use
language or type attribute. The MIME type is determined by the server instead of the script tag. Web Teaching Network

Indent
The smallest unit of indentation is 4 spaces. Do not use the TAB key, because (as of this writing in the 21st Century) there still be not a standard
For the placement of TabStops. Using spaces can cause files to become larger, but this size does not matter to the LAN, and the difference is minification eliminated.

Ruled
Do not let a line of code exceed 80 characters. When a statement cannot be written on a single line, it may be necessary to split it. Split after the operator, preferably after the comma.
The split after the operator reduces the likelihood of disguising copy-paste errors by inserting semicolons. The next line should indent 8 spaces.

Comments
Write a generous note. Leave some information available for people who need to understand what you've done (possibly yourself) next time you read it. Comments should be written well and clearly, just as they
The same code as the callout. Occasionally, a little humor is also possible. Frustration and resentment should not be written.

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

Web Teaching Network


Make annotations meaningful. Focus more on things that can't be seen right away. Do not waste the reader's time with the following content:
i = 0; Set I to zero. Webjx.com

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


Variable declaration
All variables should be declared prior to use. JavaScript does not force this, but doing so will make the program more readable and will allow the probe to become implicitly globals
variable is easier.

Web Teaching Network

The Var statement should be the first statement in the method body. Webjx.com

Each variable declaration should have its own line and a comment. They should be arranged in alphabetical order.
var currententry; Currentyly Selected table entry
var level; Indentation level
var size; Size of Table webjx.com

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

Use global variables as little as possible. An implicit global variable should never be used.

Method declaration
All methods should be declared before they are used. The internal method should be located behind the Var statement. This makes it more clear which variables are included in its scope.


There should be no spaces between the method name and the (left parenthesis) of the argument list. There is a space between ")" (right parenthesis) and "{" (opening curly braces).
The method body itself indents 4 spaces. The "}" (closing brace) 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 the method and object literals in JavaScript can be placed anywhere in the allowed expression. It uses internal methods and complex
Structure provides the best readability.
function Getelementsbyclassname (className) {
var results = [];
Walkthedom (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 literal is anonymous, there should be a space between the function and (left parenthesis). If you omit a space, it may appear that the method name is
"Function", which is wrong.
Div.onclick = function (e) {
return false;
};
that = {
Method:function () {
return this.datum;
},
datum:0;
};

Use the global approach as little as possible. Webjx.com

Named
The name should be 26 uppercase and lowercase letters (a.. Z, A.. Z), consisting of 10 digits (0.. 9) and _ (underline). Do not use international characters because they may be difficult to read or not to
It's easy to understand anywhere. Do not use the $ (dollar sign) or \ (backslash symbol) in the name.

Do not use _ (underline) as the first letter of the name. It is sometimes used to represent private, but it does not actually provide privacy.
If it's important to be private, use private members that provide privacy.
Avoid conventions that demonstrate a lack of competence. Web Teaching Network

Most variables and method names should start with lowercase letters.

Constructors that must use the new prefix should start with an uppercase letter. JavaScript does not omit the new times compile-time warning or runtime warning.
Bad things happen when you don't use new, so capitalizing the first-letter specification is the only defense we have.

Global variables should all use uppercase letters. (JavaScript has no macros or constants, so there's not a lot of scenarios that require uppercase letters to represent the characteristics of JavaScript) Web teaching Network

Statement

Simple statement
Each line should contain at least one statement. Add a ";" at the end of each simple statement. (semicolon). Note that an assignment statement that assigns values to method literals or object literals is still
An assignment statement, so you must also end with a semicolon.


JavaScript allows any expression to be used as a statement. This can result in some errors, especially when inserting a semicolon. The only expression that can be used as a statement is an assignment expression and a
Invokes an expression. Web Teaching Network

Compound statement
A compound statement is a statement that contains a list of statements surrounded by "{}" (curly braces).
1, the enclosing statement should be indented another 4 spaces.
2, "{" (opening curly brace) should be at the end of the line at which the compound statement starts.
3, "}" (closing brace) should be a new line and align with the starting position of the line where "{" matches
4, when a statement is part of a control structure, all statements should be surrounded by parentheses, even if it is a single-line statement, such as an if or a for statement. This makes it easier to add statements and does not cause starling.

Label
The statement label is optional. Only the following statements need to be labeled: While,do,for,switch. Web Teaching Network

Return statement
A return statement with a value should not surround the value with "()" (parentheses). The return value expression must be on the same line as the Returns keyword to avoid inserting a semicolon.

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

Webjx.com


if (condition) {
statements;
} else {
statements;
Web 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;
Web Teaching Network

For (variable in object) {
statements;
}

The first format should be used in several arrays.

The second format should be used with objects. Note the members that are added to the object's prototype will be included in the traversal. By using the hasOwnProperty method to differentiate between objects
The members are wise:
For (variable in object) {
if (Object.hasownproperty ()) {
statements;
}
}

Webjx.com


While statement
The while statement should use 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 use the ";" (semicolon) end. Webjx.com

Switch statement
The switch statement should have the following format:
switch (expression) {
Case expression:
statements;
Default
statements;
}

Each case is aligned with the switch, which avoids excessive indentation. Webjx.com

Each set of statements (except default) should end with Break,return or throw. Don't fall through.

Webjx.com

Try Statement
The try statement should use the following format:
try {
statements;
} catch (variable) {
statements;
}

Web Teaching Network

try {
statements;
} catch (variable) {
statements;
finally {
statements;
} webjx.com


Continue statement
Do not use the Continue statement. It makes the control process of the method blurred.

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 situations:
1, the keyword should be separated by a space after the word "(" (left parenthesis).
while (true) {

2, do not have spaces between the method name and the (left parenthesis) of the method. This facilitates distinguishing between keywords and method calls.
3, all two-dollar operators, except "." (dots), "(left parenthesis), and" ["(left bracket) should be separated by an empty cells and operand.
4, the unary operator and operand should not be separated by a space, except that the operator is a word, such as typeof.
5,for Statement control part of each ";" (semicolon) should be followed by a space.
6, each "," (comma) should be followed by a space.

Additional Suggestions

{} and []
Replace the new Object () with {}. Replace the new Array () with [].
An array is used when the member name is a contiguous integer. Use an object when the member name is any string or name. Web Teaching Network

Comma operator
Do not use the comma operator except for the strict use of the control section of the for statement. (This is not appropriate for the comma operator, it should be used for object literals, array literals, VAR statements, and parameters
List. )

Block scope
In JavaScript, the block has no scope, only the method has scope. Do not use blocks, except compound statements must be used outside. Webjx.com

An assignment expression
Do not assign values in the conditional part of the IF and while statements. Do not write code that is not understandable.

Webjx.com


= = = and!== operators
It is better to always use the = = = and!== operators. the = = and!= operators do type casts. In particular, do not use = = to compare with the "false" value. Webjx.com

Confusing add-and-subtract
Be careful not to "+" or "+ +" after "+". The pattern was confusing. Insert parentheses between them to make your intentions clearer.
Total = subtotal + +myinput.value;

is better written as

Total = subtotal + (+myinput.value);

This "+ +" will not be read incorrectly as "+ +".

Webjx.com

The Evil eval
The Eval method is the most abused feature in JavaScript. Do not use it.
Eval has an alias. Do not use the function constructor. Do not pass strings 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.