Front-end code coding and Design Specification Series--JAVASCRIPT Programming specification

Source: Internet
Author: User
Tags naming convention

1 Document Information

Entry

Content

Project number

General

Project name

General

Title

JavaScript Programming specification

Category

Specification document

Current

Trial draft

Summary

Current version

V1.0

Date

2015/11/9

Author

Xu Weijian (Xuweijian)

Document owner

Internal disclosure

File

Front End Specification Series-javascript. docx


2 Revision History

number

rev.

revision summary

revision

date

pre-revision

version number

revised

version number

V0001

Xu Weijian

Programming specification file preparation, draft trial version published

2015/11/10

V1.0


Specification Preface

Good programming standards are essential for the development and maintenance of software. Not only can he improve the readability, reliability, effectiveness, robustness of the code, but it also helps developers develop and maintain code. For a team to collaborate on a project, a change in staff, a good programming specification, helps follow-up developers and novices quickly understand what the project code is going to mean.

1 Range

This specification provides rules and recommendations for typesetting, naming, declaring, scoping, and some special symbols when programming with JavaScript.

This specification is intended for products and projects that are programmed using JavaScript language.

2 Terminology and Definitions

Rule: The principle that must be adhered to when programming.

Recommendation: A principle that must be considered when programming.

Format: A description of this canonical format.

Description: Make the necessary explanations for this specification or recommendation.

Example: Examples of this specification or recommendation are given in terms of positive and inverse two.

1 Naming conventions 1.1 basic rules

The naming of the specification makes the program easier to read and easier to understand. They can also provide some information on identifying features, which helps to better understand the code and the application.

1) Rule one: use full English descriptors that can accurately describe variables, functions, prototypes (prototype). It is forbidden to use Hanyu Pinyin, unrelated words and Chinese characters for naming, examples: firstname,listallusers or corporatecustomer, etc.;

2) rule two: minimize the use of abbreviations, but if must be used or the name is too long (no more than 25 letters), when using public abbreviations and customary abbreviations, such as implementation (implement) can be reduced to write impl, managers (manager) can be MGR and so on, strictly prohibit misuse of abbreviations;

3) rule three: variable naming must start with a lowercase letter, named using the Camel naming convention;

4) Rule four: method names must be named using verbs or verb phrases, examples: getidcname (), export (), etc.;

5) rule five: avoid names that are similar or differ only in case, so that systems that are not strictly case sensitive are considered to be the same name;

6) rule six: Avoid naming contains numbers, but you can use 2 to denote to,4 for, and the other end uses a number to denote the same series of exceptions, such as Var$td_1 = $ ('. Grid TD ') [1];

7) rule seven: class name, constructor, common object instance, and so on.

var Mycommon = {

Getsmallclassfrombigclass:function () {}

}

1.2 Related recommendations

The following recommendations are not necessary to follow, but need to be considered

1) recommendation one : If the variable is set to a private variable, the function is a private function, then an underscore is added before the label; public variables and functions are not underlined

Example one:

var MyClass = function () {

var _thistotal = 0;

var _dosomething = function () {};

This.getthistotal = function () {

return _thistotal;

};

};

var myclassinstance = new MyClass ();

Myclassinstance.total = myclassinstance. Getthistotal ();

Example two:

function MyClass () {

this._thistotal = 0;

this._dosomething = function () {};

}

MyClass.prototype.getThisTotal = function () {

return this._thistotal;

};

var myclassinstance = new MyClass ();

Myclassinstance.total = Myclassinstance.getthistotal ();

2) recommendation two : The variable name preceded by "is" should be a Boolean value, the same as "has", "can" or "should" is also true;

3) recommendation three : Repeat variables are recommended for "I", "J", "K" (and so on) names of variables;

4) recommendation four : Global variables, constants should all uppercase;

5) recommendation Five : The term "initialize" or "init" as a variable name should be a class or other type of variable that has been instantiated (initialized), or a function that should be initialized.

2 Code Organization specification

Basic principles : Conducive to personal development, easy to communicate with each other.

"description": Due to personal habits and editors can be set up to form their own unique style, but must be consistent, and conform to the basic rules, recommendations and formats.

2.1 Indent

Principle:

(1) The code is indented with tab (4 characters), in the editor, The tab is set to the same length, otherwise the tab length will not be affected by different editors or settings, which affects the formatting of the whole program code;

(2) the code in the same code block is aligned, the code block described here, including but not limited to: function, if Else statement, while, for, and so on, that is, the use of {} surrounded by code.

2.1 Notes

principle: Do not begrudge code comments, important functions, variables must be added comments, special functions, variables, constants must be added comments.

The format of the note can be seen as follows:

1) Variable Comment:

Initialize serial number

var index = 0;

var index = 0; Initialize serial number

2) function comments, including a. function description and its function description; b. Parameter descriptions should include type, parameter name, parameter description, and the return value needs to be described appropriately for the return value:

/**

* Binding Events

* @param {Object} $detailDom current Change Details page body DOM Object

* @return NULL

*/

function _bindevent ($detailDom) {

/**

* View line Details

* @param {jqueryobject} $grid list Dom container

* @param {String} selector need to add a selector for the details link

* @param {Boolean} needspecialid need to specify a different specific ID, default does not pass, that is false

* @param {String} specialidname Needspecialid is true, this value must be passed, that is, the property name of the specified ID

* @return {Boolean} result operation succeeded

*/

Viewdetail:function ($grid, selector, Needspecialid, specialidname) {

var = this;

3) file comments, which should include the file description, feature description, and author, plus time to create:

/**

* This JS implementation of the Line Renewal Application page all functions

* @author Xuweijian

* @date 2015/10/12 15:25:33

*/

$ (function () {

4) Line comment With block comment: Use//... Annotation method to annotate what needs to be indicated, and to annotate what needs to be indicated by using the/** and */comment methods.

3 Code Specification 3.1 variable code specification

principle : In accordance with the naming rules, the following rules should be adhered to,

(1) Declare multiple variables, separate the variables with commas, and suggest adding a space between the comma and the variable to avoid being too crowded, or a newline declaration (you can add a comment to a variable at this point!). ),

Example one:

var name = ', value = ', title = ';

Example two:

var name = ' ',

Value = ',//comment

title = ";

(2) Variable declaration, should be clear about the type of variables, can immediately assign value, as far as possible to avoid the type of variables in the process of being converted;

(3) Try to avoid the magic number (magicnumbers), they should use constants to replace;

(4) The declaration variable must be added to the VAR keyword, otherwise it will become a global variable (document or Window), and thus become the pollution of the global variables;

3.2 Function Encoding Specification

Principles :

(1) All functions are declared before use, and the declaration of the inner function is followed by the Var statement;

(2) Do not declare a function within the block of statements (If...else, etc.);

Its coding style should follow these tips:

1) recommendation one : Do not leave a space between the function name and the parameter ();

2) recommendation two : The parameter list is separated by commas, and a space is left between the comma and the parameter;

3) recommendation three : Use the right-hand minimalist mode, and leave a space between {;

4) recommendation four : Avoid too many parameters, generally not over 5, too much use of the object incoming;

5) recommendation five : Anonymous functions should not wrap, such as: $ (' #id '). Bind (function () {...}); The parameters in the anonymous function should not be wrapped, the body of the function follows the preceding suggestions and principles;

function outer (c,d)

{

var e = c * D;

function inner (A, B)

{

Return (E * a) + B;

}

Return inner (0, 1);

}

Minimalist mode

function outer (c,d) {

var e = c * D;

function inner (A, b) {

Return (E * a) + B;

}

Return inner (0, 1);

}

In the body of the function, we should follow these recommendations:

1) recommendation one : avoid providing multiple exits;

Do not use this method, it will be difficult to find the exit point when the processing program segment is long

if (condition) {

return A;

} else {

return B;

}

It is recommended to use the following methods

var result = null;

if (condition) {

result = A;

} else {

result = B;

}

return result;

2) recommendation two : the function body in the code should not be too long, generally not more than 100 lines;

3.3 Expressions and statements

Principles : expressions and statements should be clear, concise, easy to read and understand, and avoid the use of obscure statements. Use parentheses to express the precedence of an expression.

3.3.1 Control Statements

1) recommendation One : if there is a constant in the judgment, then the constant should be set to the right side of the judging formula. Such as:

if (true = = ISAdmin ()) ...

if (null = = user) ...

2) recommendation two : Boolean type judgment statement try to define the condition comparison value True/false

Do not recommend using

if (Iscond) ...

if (!iscond) ...

Try to use

if (true = = Iscond) ...

if (false = = Iscond) ...

if (true! = Iscond) ...

The coding style should follow these recommendations:

(1) recommendation one : The If...else if...else statement must use {} to enclose the execution statements after each judgment condition.

(2) recommendation two : If...else if...else should be empty between parentheses and curly braces;

(3) recommendation three : The condition of the variable and "= =", "= = =" between should be empty;

(4) recommendation four : type-determined variables, when compared, should use strict equality character "= = =", that is, "0" ===0 comparison value is false.

3.3.2 Loop Statements

Principles :

(1) The loop must have a condition or statement to terminate the loop, to avoid the cycle of death.

(2) When multilayer loops are nested, the counter variable is not in conflict.

(3) Notice whether the loop condition changes during the execution of the loop, and if so, the value of the loop condition must be obtained before the loop is executed and not executed at each loop.

(4) Considering the efficiency of the operation, the cyclic condition value should be obtained before the cyclic execution.

recommendation :

(1) Use the most basic for loop to avoid using the for ... in loop;

(2) for ... in loops can be used for object/map/hash traversal, and for-in loops for arrays sometimes make mistakes, not recommended;

(3) The conditional statement in the For loop should not perform an operation (such as a calculation) every time, and should be implemented in the initial statement;

The value of length per query is not recommended

for (var i = 0; i < data.length; i++) {

}

We recommend assigning a variable in the initial statement

for (var i = 0, len = data.length; i < Len; i++) {

}

3.3.3 Statement Specification

Principles :

(1) Except that the last statement of a block of statements can have no semicolon ";" , each statement must end with a semicolon to avoid parsing failure after code compression.

(2) When there is only one statement in the code block, the curly braces should not be omitted, as

if (null = = $tab) {

return; Although there is only one statement, you should not omit {}

}

3.3.4 Operator Specification

Principles :

(1) The variables on both sides of the assignment symbol and the comparison symbol should be on the same line and not be wrapped;

(2) strings use single quotation marks (') better than double quotation marks ("), especially when creating a string containing HTML code;

Class 3.4, object and prototype chain specification

Principles :

(1) Use the array and object literal syntax without using the array and object Constructors (NewArray ()) to avoid errors due to improper communication of parameters;

(2) The naming specification is referred to in section 1th of the naming specification;

Coding style, recommended as follows:

1) Compare long identifiers or values, and do not align them manually to make the code look good. Such as:

Correct_object.prototype = {

a:0,

B:1,

Lengthyname:2

};

Do not do this:

Wrong_object.prototype = {

a:0,

B:1,

Lengthyname:2

};

2) The attribute name should not be crowded between the attribute values, and should be empty between the colon ":" and the attribute value;

3.5 Error Handling

Basic Principles :

(1) The usual rule is that the system is in a normal state and the user is normally operating without any exception.

(2) Do not capture predictable errors.

(3) try{for unforeseen or difficult to resolve errors ...} catch (E) {..} Capture processing.

3.5.1 Predictable Error

A predictable error is not captured, but is avoided by a condition before the error occurs, such as:

If DIV1 is not checked for null, a missing object error is thrown when it is null

document.getElementById ("Div1"). style.width = 100;

Checking objects in advance

var objDiv1 = document.getElementById ("Div1");

if (objdiv1!=null) {

ObjDiv1.style.width = 100;

}

3.5.2 Unforeseen errors

Capturing is required for unpredictable or hard-to-resolve errors due to browser or script parser bugs, such as:

try{

Xmlhttp.open ("GET", Url,not_async);

}catch (e) {

Console.log (e.description);

}

"description": For a caught error The general situation must give feedback processing, such as Console.log (), unless it is necessary to alert the user, otherwise the alert () should not be used.

4 JavaScript Other specifications

The following specifications are the principles that must be followed, except as indicated in the recommendations and formats:

(1) eval is a demon. Eval is the easiest way to misuse JavaScript and avoid using it.

(2) do not pass string arguments to SetTimeout or setinterval, you should use function arguments.

(3) This is used only in object constructors, methods, closures.
The semantics of this is very special. Sometimes it refers to a global object (most of the time), the caller's scope, the node in the DOM tree (when the event handler is added), the newly created object (using a constructor), or another object (if the function is called () or Apply ()). It is easy to make mistakes when used.

"description": in the inline function the caller who wants to use the outer function must assign the outer caller to a variable, usually self.

(4) Do not use with () {}.

(5) Do not modify the built-in objects, such as Object.prototype and Array.prototype prototype;

(6) Use Join () to create a string.

This is usually used in this way, but it is very slow under IE:

function listhtml (items) {

var html = ' <div class= ' foo ' > ';

for (var i = 0, len = items.length; i < Len; ++i) {

if (i > 0) {

HTML + = ', ';

}

HTML + = itemhtml (Items[i]);

}

HTML + = ' </div> ';

return HTML;

}

You can do this in the following ways:

function listhtml (items) {

var html = [];

for (var i = 0, len = items.length; i < Len; ++i) {

Html[i] = itemhtml (Items[i]);

}

Return ' <div class= ' foo ' > ' + html.join (', ') + ' </div> ';

}

Description: The array is used as the string constructor and then converted to a string by a join ('). However, as the assignment operation is faster than the push () of the array, the assignment operation is used as much as possible.

"References"

[1] JavaScript programming specification. Http://wenku.baidu.com/view/f3a4cde95ef7ba0d4a733b38.html

[2] Google JavaScript Code specification Guide. Http://wenku.baidu.com/view/3a045b66b84ae45c3b358c18.html?re=view

[3] JS code specification. Http://wenku.baidu.com/view/ccd97ba20029bd64783e2c0e.html

[4] JavaScript programming specification. Http://wenku.baidu.com/view/b6e6a7d376eeaeaad1f3301e.html

Front-end code coding and Design Specification Series--JAVASCRIPT Programming specification

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.