


Dojo Javascript Programming Standards Standardize your own JavaScript writing_Basic knowledge
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:
|
Rules |
Comments
|
||||||||||||||||||||||||||||
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 |
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:
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:
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:
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
- Variables must be declared and initialized before they can be used, even if they are of NULL type.
- Variables cannot be ambiguous.
- Related variable sets should be placed in the same code block, and unrelated variable sets should not be placed in the same code block.
- Variables should try to keep the minimum lifetime.
- Specifications for looping/repeating variables:
- If you only have a loop control block, you must use a FOR loop.
- Loop variables should be initialized before the loop starts; if using a FOR loop, use the FOR statement to initialize the loop variables.
- “do … while” statements are allowed.
- "break" and "continue" statements are still allowed (but please be aware).
- Conditional expression
- Complex conditional expressions should be avoided as much as possible, and temporary Boolean variables can be used if necessary.
- The nominal case SHOULD be put in the “if” part and the exception in the “else” part of an “if” statement.
- Blocks in conditional expressions should be avoided.
- Miscellaneous
- Try to avoid magic numbers, they should be replaced by constants.
- Floating point variables must specify one decimal place (even if it is 0).
- 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:
while (!isDone){
doSomething();
isDone = moreToDo();
}
IF statement should look like this:
if (someCondition){
statements;
} else if (someOtherCondition){
statements;
} else {
statements;
}
A FOR statement should look like this:
for (initialization; condition; update){
statements;
}
WHILE statement should look like this:
while (!isDone) {
doSomething();
isDone = moreToDo();
}
DO … WHILE statement should look like this:
do {
statements;
} while (condition);
SWITCH statement should look like this:
switch (condition) {
case ABC:
statements;
// fallthrough
case DEF:
statements;
break;
default:
statements;
break;
}
The TRY … CATCH statement should look like this:
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
- operator is recommended to be separated by spaces (including ternary operator).
- 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
- 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
- Comma (,) is recommended to be separated by whitespace.
- Colon (:) It is recommended to use white space to separate.
- Dot (.) at the end is recommended to be separated by white space.
- Dot (.) Avoid using whitespace at the front.
- Function calls and methods avoid using whitespace, for example: doSomething(someParameter); // instead of doSomething (someParameter)
- Use blank lines between logical blocks.
- Statements are recommended to be aligned to make them easier to read.
Notes
- Jerky code There is no need to add comments. First you need to rewrite Them.
- Please use English for all comments.
- From solved solutions to untapped features, comments must be relevant to the code.
- After a large number of variable declarations must be followed by a comment.
- The comment needs to explain the usefulness of the code snippet, especially the following code snippet.
- 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
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
{
// 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.
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
- 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 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

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft