Home > Web Front-end > JS Tutorial > body text

Dojo Javascript Programming Standards Standardize your own JavaScript writing_Basic knowledge

WBOY
Release: 2016-05-16 16:32:49
Original
1228 people have browsed it

Foreword

The advantages of good JavaScript writing habits are self-evident. Today Bingo recommends Dojo Javascript programming specification to everyone. It is a very good Javascript programming style specification. It is recommended that everyone can learn from this specification to write Javascript. Thanks to i.feelinglucky for the translation.

Preface

Any violation to this guide is allowed if it enhances readability.

All code should be made easy for others to read.

Quick Reading Reference

Core API Please use the following style:

结构 规则 注释
模块 小写 不要使用多重语义(Never multiple words)
骆驼
公有方法 混合 其他的外部调用也可以使用 lower_case(),这样的风格
公有变量 混合
常量 骆驼 或 大写
Structure

Rules

Comments

结构 规则
私有方法 混合,例子:_mixedCase
私有变量 混合,例子:_mixedCase
方法(method)参数 混合,例子:_mixedCase, mixedCase
本地(local)变量 混合,例子:_mixedCase, mixedCase

Module lowercase Never multiple words
Class Camel
Public methods Mixing Other external calls can also use lower_case(), this style
Public variables Mixing
Constant Camel or capital
Although the following are not necessary, they are recommended:
Structure Rules
Private method Mixed, example: _mixedCase
Private variables Mixed, example: _mixedCase
Method parameters Mixed, example: _mixedCase, mixedCase
Local (local) variables Mixed, example: _mixedCase, mixedCase


Naming convention

1. Variable names must be lowercase letters.
2. Class naming uses camel naming rules, for example:

Account, EventHandler

3. Constants must be declared in front of the object (class) or enumeration variable. Enumeration variables must be named with actual meaning, and their members must use camel naming rules or use uppercase letters:

Copy code The code is as follows:

var NodeTypes = {
Element: 1,
DOCUMENT: 2
}

4. Abbreviated words cannot use uppercase names as variable names:

getInnerHtml(), getXml(), XmlDocument
5. The command of the method must be a verb or a verb phrase:

obj.getSomeValue()
6. Public classes must be named using mixed names (mixedCase).
7. CSS variables must be named using the same public class variables they correspond to.
8. Variable attribute members of private classes must be named with a mixed name (mixedCase) and preceded by an underscore (_). For example:

Copy code The code is as follows:

var MyClass = function(){
var _buffer;
this.doSomething = function(){
};
}

9. If the variable is set to be private, an underscore must be added in front of it.

this._somePrivateVariable = statement;

10. Universal variables must use type names consistent with their names:

setTopic(topic) // The variable topic is a variable of type Topic
11. All variable names must use English names.
12. If the variable has a wider scope (large scope), it must use a global variable; in this case, it can be designed as a member of a class. On the other hand, if the scope is small or the variable is private, use concise word naming.
13. If a variable has its own implicit return value, avoid using its similar methods:

getHandler(); // Avoid using getEventHandler()

14. Public variables must clearly express their own attributes to avoid ambiguous word meanings, for example:

MouseEventHandler
, not MseEvtHdlr.
Please pay attention to this rule again, 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. Class/constructor can be named by extending the name of its base class, so that the name of its base class can be found correctly and quickly:
EventHandler
UIEventHandler
MouseEventHandler
A base class can shorten its naming on the premise of clearly describing its properties:
​MouseEventHandler as opposed to MouseUIEventHandler.

Special naming convention

The term "get/set" should not be associated with a field unless it is defined as a private variable.
Variable names preceded by "is" should be Boolean values, and similarly they can be "has", "can" or "should".
The term "compute" as a variable name should refer to a variable that has been computed.
The term "find" as a variable name shall refer to the variable for which the search has been completed.
The term "initialize" or "init" as a variable name should refer to a class or other type of variable that has been instantiated (initialized).
UI (User Interface) control variables should have the control type after the name, for example: leftComboBox, TopScrollPane.
Plural forms MUST be used to name collections.
Variable names starting with "num" or "count" are conventionally numbers (objects).
It is recommended to use variables with names such as "i", "j", "k" (and so on) for repeated variables.
Supplementary terms must use supplementary words, such as: get/set, add/remove, create/destroy, start/stop, insert/delete, begin/end, etc.
Use abbreviations for names that can be abbreviated.
Avoid ambiguous Boolean variable names, for example:
isNotError, isNotFound is illegal
It is recommended to add "Exception" or "Error" after the variable name for error classes.
If the method returns a class, the name should indicate what it returns; if it is a procedure, it should indicate what it does.

File

Please use 4 whitespace tab stops for indentation.
If your editor supports file tags, please add the following line to make our code easier to read:

// vim:ts=4:noet:tw=0:
Translation note: Foreigners use VIM editor more, you can choose to follow this article.

Code folding must look complete and logical:

Copy code The code is as follows:

var someExpression = Expression1
Expression2
Expression3;

var o = someObject.get(
Expression1,
Expression2,
Expression3
);

Note: The indentation of expressions and variable declarations should be consistent.
Note: Function parameters should be explicitly indented, 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 NULL type.
  2. Variables cannot be ambiguous.
  3. Related variable sets should be placed in the same code block, and unrelated variable sets should not be placed in the same code block.
  4. Variables should try to keep the minimum lifetime.
  5. Specifications for looping/repeating variables:
    1. If you only have a loop control block, you must use a FOR loop.
    2. Loop variables should be initialized before the loop starts; if using a FOR loop, use the FOR statement to initialize the loop variables.
    3. “do … while” statements are allowed.
    4. "break" and "continue" statements are still allowed (but please be aware).
  6. Conditional expression
    1. Complex conditional expressions should be avoided as much as possible, and temporary Boolean variables can be used if necessary.
    2. The nominal case SHOULD be put in the “if” part and the exception in the “else” part of an “if” statement.
    3. Blocks in conditional expressions should be avoided.
  7. Miscellaneous
    1. Try to avoid magic numbers, they should be replaced by constants.
    2. Floating point variables must specify one decimal place (even if it is 0).
    3. Floating point variables must specify the real part, even if they are zero (use a leading 0.).

Layout

Block

A normal code snippet should look like this:

Copy code The code is as follows:

while (!isDone){
doSomething();
isDone = moreToDo();
}

IF statement should look like this:

Copy code The code is as follows:

if (someCondition){
statements;
} else if (someOtherCondition){
statements;
} else {
statements;
}

A FOR statement should look like this:

Copy code The code is as follows:

for (initialization; condition; update){
statements;
}

WHILE statement should look like this:

Copy code The code is as follows:

while (!isDone) {
doSomething();
isDone = moreToDo();
}

DO … WHILE statement should look like this:

Copy code The code is as follows:

do {
statements;
} while (condition);

SWITCH statement should look like this:

Copy code The code is as follows:

switch (condition) {
case ABC:
statements;
// fallthrough
case DEF:
statements;
break;
default:
statements;
break;
}

The TRY … CATCH statement should look like this:

Copy code The code is as follows:

try {
statements;
} catch(ex) {
statements;
} finally {
statements;
}

Single-line IF – ELSE, WHILE or FOR statements must also have parentheses, but they can be written like this:
if (condition){ statement; }
while (condition){ statement; }
for (initialization; condition; update){ statement; }

Blank

  1. operator is recommended to be separated by spaces (including ternary operator).
  2. Avoid using whitespace to separate the following keywords:
    • 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 whitespace:
    • case
    • default
    • delete
    • function (if it is a declaration, for example: function foo(){}; )
    • in
    • instanceof
    • new
    • throw
    • typeof
    • var
  4. Comma (,) is recommended to be separated by whitespace.
  5. Colon (:) It is recommended to use white space to separate.
  6. Dot (.) at the end is recommended to be separated by white space.
  7. Dot (.) Avoid using whitespace at the front.
  8. Function calls and methods avoid using whitespace, for example: doSomething(someParameter); // instead of doSomething (someParameter)
  9. Use blank lines between logical blocks.
  10. Statements are recommended to be aligned to make them easier to read.

Notes

  1. Jerky code There is no need to add comments. First you need to rewrite Them.
  2. Please use English for all comments.
  3. From solved solutions to untapped features, comments must be relevant to the code.
  4. After a large number of variable declarations must be followed by a comment.
  5. The comment needs to explain the usefulness of the code snippet, especially the following code snippet.
  6. Comments There is no need to add on every line.

Documentation

The following provides some basic function or object description methods:

Summary: Briefly describe the purpose of this function or object
Description: A brief description of this function or class
Return: Describes what this function returns (not including the return type)
Basic function information

Copy code The code is as follows:

function(){
// summary: Soon we will have enough treasure to rule all of New Jersey.
// description: Or we could 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 code The 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?
}

Declaration of function

In some cases, function calls and declarations are invisible. In this case, we have no way to add instructions to the function (for the program to call). If you encounter this situation, you can use a class to encapsulate the function.

Note: This method can only be used when the function has no initialized parameters. If not, they are ignored.

Copy code The code is as follows:

dojo.declare(
"foo",
null,
{
// summary: Phew, this sure is relaxing, Frylock.
// description:
//Thousands of years ago, before the dawn of
// man as we knew him, there was Sir Santa of Claus: an
// ape-like creature making crude and pointless toys out
// of dino-bones, hurling them at chimp-like creatures with
// crinkled hands regardless of how they behaved the
// previous year.
// returns: Unless Carl pays tribute to the Elfin Elders in space.
}
);

Parameters



  1. Simple type
    Simple type parameters can be annotated directly in the function parameter definition.
    [cc lang="javascript"]function(/*String*/ foo, /*int*/ bar)...
    Variable type parameters
    ​ Here are a few modifiers for reference:
    ? Optional parameters
    … Said that the range of noodle parameters is uncertain
    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.
    The basic information format is: *key* description field (*key* Descriptive sentence)
    The format of parameters and variables is: *key* ~*type*~ description field (*key* ~*type*~ Descriptive sentence)
    Note: *Keyword* and ~*Type*~ can be expressed using any letters and numbers.

    Copy code The code is as follows:

    function (foo, bar) {
    // foo: String
    // used for being the first parameter
    // bar: int
    // used for being the second parameter
    }

    Variable

    Since the declaration of instance variables, prototype variables and external variables are consistent, there are many ways to declare and modify variables. The specific definition and positioning should indicate the name, type, scope and other information of the variable where it first appears.

    Copy code The 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 annotations in objects

    should be marked in the same way as object values ​​and methods, for example when they are declared:

    Copy code The code is as follows:

    {
    // key: String
    // A simple value
    key: "value",
    // key2: String
    // Another simple value
    }

    Return value

    Because a function can return multiple different (types) values ​​at the same time, a return type comment should be added after each return value. Comments can be made within the line. If all return values ​​are of the same type, indicate the return type; if there are multiple different return values, mark the return type as "mixed".

    Copy code The 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 this function or class in a function or class. If you plan to do this, you can use /*======== (= character preferably appears 5 times or more), which has the advantage of not having to add these things to the code (Annotation: Original author's Probably means code management system).

    It looks like there will be a very long comment in /*====== and =====*/. You can consider whether to delete it after the function adjustment is completed.

    Copy code The 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);
    }

    Original link: http://dojotoolkit.org/developer/StyleGuide
    Translated by: i.feelinglucky{at}gmail.com from http://www.gracecode.com

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!