JavaScript Coding Specification

Source: Internet
Author: User

Code Authoring Specification
    1. Comments and update notes

You have to annotate your code, even if no one else touches it like you. Usually, when you delve into a problem, you'll know exactly what the code is for, but when you come back in a week, you're going to have to drain a lot of brain cells to figure out how it works.

Annotations cannot go to extremes: each individual variable or a single row. However, you should usually record all functions, their parameters and return values, or any unusual techniques and methods. Think of annotations that give you a lot of hints about future readers of your code, and what the reader needs (not to read too much) is to understand your code only with comments and function attribute names. For example, when you have a five or six-line program that performs a specific task, if you provide a line of code for the purpose and why it is described here, the reader can skip the details directly. There is no hard-coded comment than code, and some parts of the code, such as regular expressions, may comment more than code.

    1. Use of spaces

The use of spaces also helps to improve the readability and consistency of your code. When writing English sentences, intervals are used after commas and periods. In JavaScript, you can follow the same logic to add an interval after a list-like expression (equivalent to a comma) and a closing sentence (relative to the "idea"). The following are some of the best spaces to use:

First: The part after the for loop semicolon separates: such as for (var i = 0; i <; i + = 1) {...}

Second: The amount of variability initialized in the For loop (I and Max): for (var i = 0, max = ten; i < max; i + = 1) {...}

Third: Separates the array items after the comma: var a = [1, 2, 3];

IV: After the object property comma and after the colon separating the property name and the property value: var o = {a:1, b:2};

V: Qualification function Parameters: MyFunc (A, B, c)

Sixth: The front of the curly brace of the function declaration: Functions MyFunc () {}

Seventh: The anonymous function is followed by: var myFunc = function () {};

Using spaces to separate all operators and operands is another good use, which means that +, -, *, =, <, >, <=, >=, ===, !==, &&, ||, += spaces are required before and after.

Easy and consistent spacing makes code easier to read, making it more "breathable"
var d = 0,
A = B + 1;
if (a && b && c) {
D = a% C;
A + = D;
}
Negative examples, missing or spaced, make the code confusing
var d = 0,
A = B + 1;
if (a&&b&&c) {
D=a% c;
a+= D;
}

    1. Naming conventions

First: Write the constructor with uppercase letters

function Myconstructor () {...} constructor function
function myFunction () {...} General functions

Second: The constants are all capitalized, and the global variable names are all capitalized. All CAPS naming global variables can enhance the practice of reducing the number of global variables while making them easy to distinguish.

Third: You can use an underscore prefix table _protected (Protection) property, with two underscore prefixes representing __private (private) attributes (just the analog representation, not really protected or private, just to alert the user). For example:

var person = {
Getname:function () {
return This._getfirst () + "+ this._getlast ();
},

_getfirst:function () {
// ...
},
_getlast:function () {
// ...
}
};

    1. Braces

4.1. Always use curly braces

Curly braces are also always used in optional code snippets. Technically, in or for if the statement is only one, curly braces are not needed, but you should always use them, which makes the code more persistent and easy to update.

A bad example
for (var i = 0; i <; i + = 1)
alert (i);
A good example
for (var i = 0; i <; i + = 1) {
alert (i);
}

Including If...else ... Statement as well. Curly braces are always used.

4.2. The left curly brace is always on the same line as the previous statement

Because the semicolon insertion mechanism (semicolon insertion mechanism)--javascript is not picky, JavaScript will help you make up your own when you choose to end a line of code without using a semicolon. This behavior can cause trouble, such as when you return an object literal, while the opening parenthesis is on the next line:

Warning: Unexpected return value
function func () {
Return
The following code does not perform
{
Name: "Batman"
}
}
Good habit.
function func () {
return {
Name: "Batman"
};
}

In summary, always use curly braces, and always put its (left curly brace) on the same line as the previous statement.

    1. Always use indent

Indent with tab tabs, because anyone can adjust their editor to display tabs in the number of spaces they like. Some people like spaces-usually four, which doesn't matter, as long as everyone in the team follows the same specification. As follows:

function outer (A, b) {
var c = 1,
D = 2,
Inner
if (a > B) {
Inner = function () {
return {
R:c-D
};
};
} else {
Inner = function () {
return {
R:c + D
};
};
}
return inner;
}

Use indentation to make your code look elegant and beautiful.

    1. numeric conversions under parseint ()

Using parseint () You can get a numeric value from a string that accepts another cardinality parameter, which is often omitted, but should not. When the string starts with "0″" it can be problematic, for example, part of the time into the form field, in ECMAScript 3, the string that starts with "0″" is treated as 8, but this has changed in ECMAScript 5. To avoid conflicting and unexpected results, always specify a cardinality parameter.

var month = "06",
Year = "09";
month = parseint (month, 10);
Year = parseint (year, 10);

Methods that perform better than the parseint () method can also replace the parseint () method, as follows:

+ "08"//result is 8
Number ("08")//8

    1. Avoid using eval ()

If you are using eval () in your code now, remember that the mantra "eval () is the Devil". This method accepts arbitrary strings and treats them as JavaScript code. When the problematic code is known in advance (not at runtime), there is no reason to use eval (). If the code is dynamically generated at run time, there is a better way to achieve the same goal without using Eval. For example, it would be much easier to access dynamic properties using square brackets notation:

Reverse Example
var property = "Name";
Alert (eval ("obj." + property));

better.
var property = "Name";
Alert (Obj[property]);

    1. Avoid implicit type conversions
    2. Switch mode
    3. It's best not to extend the built-in prototypes
    4. Correct use of for-in loops
    5. Correct use of the For loop
    6. Pre-parsing of variables (problems with VAR dispersion)
    7. Single var form
    8. Accessing global objects
    9. Forget the side effects of the VAR keyword
    10. Problems with global variables
    11. Minimum global variables

JavaScript encoding 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.