JavaScript Basic Coding Specification

Source: Internet
Author: User
Tags naming convention

1. Indent (indentation)

Indent with four Space Code tab

Where indentation is used:

function body, loop (do,while,for,for-in), if, switch, and object properties in the object literal. Example:

1 functionouter (A, b) {2     varc = 1,3D = 2,4 Inner;5     if(A >b) {6Inner =function () {7             return {8R:C-D9             };Ten         }; One}Else { AInner =function () { -             return { -R:c +D the             }; -         }; -     } -     returnInner; +}

PS: The code is not indented and is basically unreadable. The only bad thing is an inconsistent indentation, because it looks like it follows the norm, but it may be accompanied by confusion and surprise along the way. It is important to use indentation in a canonical manner.

2. curly Braces {}

Curly braces (also weigh brackets, hereinafter) should always be used, even when they are optional. 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.

3.

3. Space (white space)

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").

Where spaces are suitable for use include:

    • For loop semicolon separated parts: such as for (var i = 0; I < + + + + 1) {...}
    • Variable initialized in the For loop (I and Max): for (var i = 0, max = ten; i < max; i + = 1) {...}
    • After separating the comma of the array entry: var a = [1, 2, 3];
    • After the object property comma and after the colon that separates the property name and the property value: var o = {a:1, b:2};
    • Qualification function Parameters: MyFunc (A, B, c)
    • The front of the curly brace for the declaration of functions: function MyFunc () {}
    • anonymous function expression: var MyFunc = function () {};

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

The last one to note is a space-curly brace spacing. It is best to use spaces:

    • function, If-else statement, Loop, front of the left curly brace of the object literal ({)
    • Right curly brace (}) between else or while

A small amount of space is used to increase the size of the file, but compression does not have this problem.

One of the most frequently overlooked code readability is the use of vertical spaces. You can use blank lines to separate code units, just as you would use paragraph breaks in a literary work.

4. Naming conventions

Another way to make your code more predictable and maintainable is to use a naming convention. This means that you need to name your variables and functions in the same way. Here are some suggested naming conventions that you can use as they are, or adjust to your preferences. Similarly, it is more important to follow a specification than what a specification is.

Write the constructor in uppercase letters (capitalizing constructors)

JavaScript does not have a class, but there is a constructor for the new call:

1 varadam = newPerson();

Because the constructor is still just a function, just looking at the function name can help tell you whether this should be a constructor or a normal function. When naming constructors, uppercase letters are suggestive, and functions and methods that use lowercase names should not be called with NEW:

1 functionMyConstructor() {...}
2 functionmyFunction() {...}
Delimited words (separating Words)

When your variable or function name has multiple words, the separation of the best words follows a uniform norm, and one common practice is called "camel", which is the lowercase words, capitalized in the first letter of each word.

For constructors, you can use the large hump-type naming method (upper camel case), such as Myconstructor (). For function and method names, you can use the small hump-like nomenclature (lower camel case), such as MyFunction (), CalculateArea (), and Getfirstname ().

What if the variable is not a function? Developers usually use small hump-style nomenclature, but there is another way to do all of the words with lowercase underline connections: For example, first_name, Favorite_bands, and Old_company_name, which help you visually differentiate functions and other identities- Prototypes and objects.

The properties and methods of ECMAScript use camel notation, although the name of a multi-word property is rare (the lastindex and ignorecase properties of a regular Expression object).

Other naming forms (other naming Patterns)

Sometimes, developers use naming conventions to compensate for or replace language features. For example, there are no methods for defining constants in JavaScript (although some built-in like number, max_value), so developers use the full capitalization specification to name variables that do not change in the program's life cycle, such as:

1 // 珍贵常数,只可远观
2 varPI = 3.14,
3     MAX_WIDTH = 800;

There is another formula for full capitalization: The global variable name is all capitalized. All CAPS naming global variables can enhance the practice of reducing the number of global variables while making them easy to distinguish.

Another way to simulate functionality using a specification is private members. While it is possible to implement true private in JavaScript, developers find it easier to use only one underscore prefix to represent a private property or method. Consider the following example:

01 varperson = {
02     getName: function() {
03         returnthis._getFirst() + ‘ ‘this._getLast();
04     },
05
06     _getFirst: function() {
07         // ...
08     },
09     _getLast: function() {
10         // ...
11     }
12 };

In this example, GetName () represents a common method, a partially stable API. _getfirst () and _getlast () indicate the private. They are still normal public methods, but using the underscore prefix to warn the consumer of the person object that these methods are not guaranteed to work in the next version is not directly available. Note that JSLint does not have a bird underline prefix unless you set the Noman option to: false.

The following are some common _private specifications:

    • Use a trailing underline to represent private, such as Name_ and Getelements_ ()
    • Using an underscore prefix table _protected (Protection) attribute, the two underscore prefixes represent __private? (private) Properties
    • Some of the built-in variable properties in Firefox are not part of the technical portion of the language, using two front underscores and two after underscores, such as: __proto__ and __parent__.
Note (Writing Comments)

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.

Obviously, annotations cannot go to extremes: each individual variable or a single line. 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 code, and some parts of the code, such as regular expressions, may be commented more than the code.

The most important habit, but also the hardest to follow, is to keep the annotations up-to-date, because outdated comments are more misleading than no comments.

Source: http://www.nowamagic.net/librarys/veda/detail/1629

JavaScript Basic Coding 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.