Preface
The advantages of good JavaScript writing habits are self-evident. Today, Bin Go recommends Dojo Javascript programming specifications to you, which are quite good Javascript programming style specifications. It is recommended that you learn from this specification to write Javascript. Thanks to i.feelinglucky for the translation.
sequence
Any violence to this guide is allowed if it enhances readability.
All codes must be made easy for others to read.
Quick read reference
Core API Please use the following style:
| structure | rule | Comments |
| Module | lower case | Do not use multiple semantics (Never multiple words) |
| kind | camel | |
| Public methods | mix | Other external calls can also use lower_case(), in this style |
| Public variables | mix | |
| constant | Camel or capital |
Although the following is not necessary, it is recommended to use:
| structure | rule |
| Private method | Mixed, example: _mixedCase |
| Private variables | Mixed, example: _mixedCase |
| Method parameters | Mixed, example: _mixedCase, mixedCase |
| Local variable | Mixed, example: _mixedCase, mixedCase |
Naming Specifications
1. The variable name must be lowercase letters.
2. The naming of classes uses camel naming rules, such as:
Account, EventHandler
3. Constants must be declared in the front of an object (class) or enumeration variable. The naming of an enumeration variable must have practical significance, and its members must use camel naming rules or capitalize:
The code copy is as follows:
var NodeTypes = {
Element : 1,
DOCUMENT: 2
}
4. Abbreviated words cannot use capital names as variable names:
getInnerHtml(), getXml(), XmlDocument
5. The command of the method must be a verb or a verb phrase:
obj.getSomeValue()
6. The naming of public classes must be named using mixed names (mixedCase).
7. The name of a CSS variable must use its corresponding same public class variable.
8. The variable attribute members of the private class must be named with a mixed name (mixedCase) and underlined (_). For example:
The code copy is as follows:
var MyClass = function(){
var _buffer;
this.doSomething = function(){
};
}
9. If the variable is set to private, it must be underscoreed before it.
this._somePrivateVariable = statement;
10. Common variables must use a type name that is consistent with their name:
setTopic(topic) // Variable topic is a variable of type Topic
11. All variable names must use English names.
12. If a variable has a wide scope (large scope), global variables must be used; at this time, it can be designed as members of a class. If the relative scope is smaller or private variables, use concise words to name it.
13. If a variable has its implicit return value, avoid using its similar methods:
getHandler(); // Avoid using getEventHandler()
14. Public variables must clearly express their own attributes to avoid ambiguity in the meaning, such as:
MouseEventHandler
, not MseEvtHdlr.
Please pay attention to this provision 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/constructors can be named using the name that extends its base class, so that the name of its base class can be found correctly and quickly:
EventHandler
UIEventHandler
MouseEventHandler
The base class can reduce its naming while clearly describing its properties:
MouseEventHandler as opposed to MouseUIEventHandler.
Special naming specifications
The term "get/set" should not be linked to a field unless it is defined as a private variable.
The variable name preceded by "is" should be a Boolean value, and can be "has", "can" or "should".
The term "compute" as the variable name should be a variable that has been calculated.
The term "find" as the variable name should be a variable that has been found completed.
The term "initialize" or "init" as the variable name should be a class or other type of variable that has been instantiated (initialized).
UI (user interface) control variables should be followed by the name of the control type, for example: leftComboBox, TopScrollPane.
The plural number must have its common name convention (original text: Plural form MUST be used to name collections).
Variable names starting with "num" or "count" are conventionally numeric (object).
Repeat variables are recommended to use variables with names such as "i", "j", "k" (and so on).
Supplementary terms must use supplementary words, such as: get/set, add/remove, create/destroy, start/stop, insert/delete, begin/end, etc.
Try to use abbreviation if possible.
Avoid ambiguity of boolean variable names, for example:
isNotError, isNotFound is illegal
The error class recommends adding "Exception" or "Error" to the variable name.
If a method returns a class, it should indicate what it returns on its name; if it is a process, it should indicate what it did.
document
Please use 4 blank tabs to indent.
If your editor supports file tags, please add the following line to make our code easier to read:
// vim:ts=4:noet:tw=0:
Translator's note: Foreigners use VIM editors more often, so you can choose to follow this article.
Code folding must look done and be logical:
The code copy is as follows:
var someExpression = Expression1
+ Expression2
+ Expression3;
var o = someObject.get(
Expression1,
Expression2,
Expression3
);
Note: The indentation of the expression should be consistent with the variable declaration.
Note: The parameters of the function should be explicitly indented, and the indentation rules are consistent with other blocks.
variable
layout
piece
A normal code snippet should look like this:
The code copy is as follows:
while (!isDone){
doSomething();
isDone = moreToDo();
}
The IF statement should look like this:
The code copy is as follows:
if (someCondition){
statements;
} else if (someOtherCondition){
statements;
} else {
statements;
}
The FOR statement should look like this:
The code copy is as follows:
for (initialization; condition; update){
statements;
}
The WHILE statement should look like this:
The code copy is as follows:
while (!isDone) {
doSomething();
isDone = moreToDo();
}
The DO… The WHILE statement should look like this:
The code copy is as follows:
do {
statements;
} while (condition);
The SWITCH statement should look like this:
The code copy is as follows:
switch (condition) {
case ABC:
statements;
// fallthrough
case DEF:
statements;
break;
default:
statements;
break;
}
The TRY … The CATCH statement should look like this:
The code copy is as follows:
try {
statements;
} catch(ex) {
statements;
} finally {
statements;
}
Single-line IF ELSE, WHILE or FOR statements must also be included in brackets, but they can be written like this:
if (condition){ statement; }
while (condition){ statement; }
for (intialization; condition; update){ statement; }
blank
Comments
document
The following provides some basic functions or objects description methods:
Summary: A brief description of the purpose of this function or object implementation
Description: A brief description of this function or class
Return: Describes what this function returns (not including the return type)
Basic function information
The code copy 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
The code copy 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 says whiplash, just yet, cause that's a little too far,
// but, you're injured, right?
}
Declaration of functions
In some cases, the call and declaration of functions are invisible. In this case, we have no way to include instructions, etc. (for program calls) in the function. If you encounter this situation, you can use a class to encapsulate the function.
Note: This method can only be used without initialized parameters of the function. If not, they will be ignored.
The code copy 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 creativity making crude and pointless toys out
// of dino-bones, hurling them at chimp-like creativity with
// crinkled hands regardless of how they behaved the
// previous year.
// returns: Unless Carl pays fees to the Elfin Elders in space.
}
);
<h3>Parameters</h3>
<ol>
<li>Simple Type
Simple types of parameters can be directly commented and explained 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
... The parameter range of the face 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* Description sentence)
The format of parameters and variables is: *key* ~*type*~ Description field ( *key* ~*type*~ Description sentence)
Note: *Keywords* and ~*Type*~ can be expressed in any letters and numbers.
The code copy 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 declarations of instance variables, prototype variables and external variables are consistent, there are many methods to declare and modify variables. Specific definition and positioning should indicate the name, type, scope and other information of the variable at the first location where the variable appears.
The code copy 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 comments in objects
An annotation method that is consistent with object values and methods should be used, such as when they declare:
The code copy is as follows:
{
// key: String
// A simple value
key: "value",
// key2: String
// Another simple value
}
Return value
Because functions can return multiple different (types) values at the same time, each return value should be added to the comment of the return type. Comments are just commented in the line. If all return values are of the same type, the returned type is specified; if there are multiple different return values, the return type is marked as "mixed".
The code copy 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 and class in a function or class. If you plan to do this, you can use /*======= (= characters should appear 5 times or more). The advantage of this is that you don't have to add these things to the code (translator's note: the original author may mean a code management system).
This way, there will be a very long comment in /*===== and ====*/. You can consider whether to delete it after the function is adjusted.
The code copy 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