Dojo Javascript programming specifications regulate your own JavaScript writing, dojojavascript

Source: Internet
Author: User

Dojo Javascript programming specifications regulate your own JavaScript writing, dojojavascript

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:

Copy codeThe 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:

Copy codeThe 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:

Copy codeThe 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

  1. Variables must be declared and initialized before they can be used, even if they are of the NULL type.
  2. Variables cannot be ambiguous.
  3. Related variable sets should be placed in the same code block, and irrelevant variable sets should not be placed in the same code block.
  4. Keep the minimum life cycle of the variable as much as possible.
  5. Rules for loop/repeated variables:
    1. If only the loop control block is used, the FOR loop must be used.
    2. 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.
    3. "Do... The while statement is allowed.
    4. The "break" and "continue" statements are still allowed (please note ).
  6. Conditional expressions
    1. Avoid complex conditional expressions, and use temporary Boolean variables if necessary.
    2. The nominal case shocould be put in the "if" part and the exception in the "else" part of an "if" statement.
    3. Avoid adding blocks to conditional expressions.
  7. Miscellaneous
    1. Try to avoid Magic numbers, which should be replaced by constants.
    2. The floating point variable must specify the last digit (even if it is 0) after the decimal point ).
    3. 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:

Copy codeThe Code is as follows:
While (! IsDone ){
DoSomething ();
IsDone = moreToDo ();
}

The IF statement should look like this:

Copy codeThe Code is as follows:
If (someCondition ){
Statements;
} Else if (someOtherCondition ){
Statements;
} Else {
Statements;
}

The FOR statement should look like this:

Copy codeThe Code is as follows:
For (initialization; condition; update ){
Statements;
}

The WHILE statement should look like this:

Copy codeThe Code is as follows:
While (! IsDone ){
DoSomething ();
IsDone = moreToDo ();
}

DO... The WHILE statement should look like this:

Copy codeThe Code is as follows:
Do {
Statements;
} While (condition );

The SWITCH statement should look like this:

Copy codeThe 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:

Copy codeThe 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

  1. We recommend that you use spaces to separate operators (including ternary operators ).
  2. 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
  3. 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
  4. We recommend that you use commas (,) to separate them with spaces.
  5. We recommend that you use white spaces to separate colons.
  6. We recommend that you use white spaces to separate points (.) in the back.
  7. Point (.) To avoid blank spaces in the front.
  8. Avoid blank space for function calls and methods, such as doSomething (someParameter); // instead of doSomething (someParameter)
  9. Empty lines are used between logical blocks.
  10. It is recommended to align the statement to make it easier to read.

Note

  1. The raw code isNot necessaryAdded comments. First, you needRewriteThey.
  2. All comments must be in English.
  3. From the solution to the undeveloped features, commentRequiredCode-related.
  4. After a large number of variables are declaredRequiredFollow a comment.
  5. Note the usefulness of the code segment, especially the following code segment.
  6. 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

Copy codeThe 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

Copy codeThe 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.

Copy codeThe 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.
}
);

<H3> parameter <Ol>
<Li> 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.

Copy codeThe 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.

Copy codeThe 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:

Copy codeThe 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 ".

Copy codeThe 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.
Copy codeThe 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 );
}


JavaScript programming Specification

Find this article
JavaScript code specification

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 specifications?

Here's your attachment, the ECMAScript5 specification is the ECMA-262


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.