JavaScript Code Code Specification _JAVASCRIPT Skills

Source: Internet
Author: User
Tags comments eval lowercase naming convention uppercase letter hasownproperty

The long-term value of software derives directly from its coding quality. Throughout its lifecycle, a program may be read or modified by many people. If a program can clearly show its structure and features, it can reduce the likelihood of errors in future modifications. Programming specifications can help programmers increase the robustness of their programs.

All of the JavaScript code is exposed to the public. So we should guarantee the quality. It's important to keep neat.

JavaScript files

JavaScript programs should be stored independently in a file with a. js suffix.

JavaScript code should not be included in an HTML file unless it is a section-specific code that belongs only to this section. JavaScript code in HTML can significantly increase file size, and it cannot be cached and compressed.

Filename.js should be put to the back of the body as far as possible. This reduces the problem of loading the script and causing other page content to load. It is also not necessary to use the language or type attribute. MIME types are determined by the server, not by the Scripttag.

Indent

The indent unit is four spaces. Avoid using the TAB key to indent (even if it is now 21st century), and there is always no uniform tab length standard. Although using spaces increases the size of the file, it is almost negligible in the LAN and can be eliminated during the minimization process.

Length per line

Avoid more than 80 characters per line. When a statement is not written in one line, consider a line break. In the operation symbol, preferably a comma after the line. Wrapping a line after the operator reduces the chance that the error caused by the copy paste will be masked by semicolons. The next line should indent 8 spaces.

Comments

Don't skimp on annotations. It is useful to leave a message for people who need to understand your code later (perhaps yourself). Annotations should be written as well and clear as the code they annotate. The occasional little humor is even better. Remember to avoid being lengthy or emotional.

It is also important to update annotations in a timely manner. Incorrect annotations make the program more difficult to read and understand.

Make annotations meaningful. The emphasis is on explaining the logic that is not easy to understand immediately. Don't waste your time reading a reader like this:

  i = 0; Let I equal 0

Use Single-line comments. Block annotations are used to annotate formal documents and unwanted code.

Variable declaration

All variables must be declared before they are used. JavaScript does not have to be forced to do this, but doing so makes the program easier to read, and it is easy to find those variables that are not declared (they are compiled into global variables).

Place the Var statement in the header of the function

It is a good idea to put the declaration statement of each variable on a single line and add a note. All variables are sorted alphabetically.

  var currententry; The current selection    var level;    Indent degree    var size;     Table size

JavaScript does not have a block range, so defining variables inside a block can easily cause misunderstandings among c/c++/java programmers. Define all the variables in the header of the function.

Minimize the use of global variables. Do not allow local variables to overwrite global variables.

function declaration

All functions are declared before they are used. The declaration of the inner function follows the VAR statement. This helps to determine which variables are within the scope of the function.

There should be no spaces between the function name and ((opening parenthesis). (closing parenthesis) and a space should be inserted between {(opening curly braces) of the starting program body. The function program body should indent four spaces. The right curly brace is aligned to the head of the line of code that declares the function.

  function outer (c, D) {    var e = c * D;    function inner (A, b) {return      (E * a) + B;    }    Return inner (0, 1);  }

This type of writing can be used normally in JavaScript, because in JavaScript, functions and object declarations can be placed where any expression allows. And it gives the best readability for inline functions and mixed structures.

  function Getelementsbyclassname (className) {    var results = [];    Walkthedom (document.body, function (node) {      var A;         Class array group      var c = node.classname;//Node class name      var i;         Loop counter//IF the node has a class name, then split it into a list of simple names.//If any of them match the requested n Ame, then append the node to the set of results.      if (c) {        a = C.split (');        for (i = 0; i < a.length i = 1) {          if (a[i] = = className) {            Results.push (node);            break;          }}}    );    return results;  }

If the function is an anonymous function, there should be a space between functions and ((opening parenthesis). If you omit a space, you will be given the function of the human senses.

  Div.onclick = function (e) {return    false;  };  This = {    method:function () {return      this.datum;    },    datum:0  };

Try not to use global functions.

Named

The variable name should be 26 uppercase and lowercase letters (a.. Z,a.. Z), consisting of 10 digits (0..9), and _ (underline). Avoid the use of internationalized characters, such as Chinese, because they are not easily read and understood anywhere. Do not use $ (dollar sign) or (backslash) in the name.

Do not use _ (underline) as the first character of the variable name. It is sometimes used to represent private variables, but in practice JavaScript does not provide the functionality of private variables. If the private variable is important, use the form of a private member. You should avoid using this misleading naming convention.

Most variable names and methods should begin with lowercase letters.

The constructor name that must be used in conjunction with new should begin with an uppercase letter. JavaScript does not have any compilation errors or run errors when new is omitted. Forgetting to add new makes bad things happen (such as being a normal function), so capitalizing the constructor name is the only way we can try to avoid this happening.

Global variables should all be capitalized. (JavaScript does not have macros or constants, so it won't cause misunderstanding)

Statement

Simple statement

Each row contains at most one statement. put; (semicolon) at the end of each simple statement. Note that a function assignment or an object assignment statement is also an assignment statement and should end with a semicolon.

JavaScript can think of any expression as a single statement. It's easy to hide some errors, especially those that mistakenly add semicolons. An expression should be treated as a separate statement only when it is assigned and invoked.

Compound statement

A compound statement is a sequence of statements that is contained in {} (curly braces).

    • * The quoted statement must indent four spaces more.
    • * {(opening brace) should be at the end of the compound statement's implementation.
    • *} (right curly brace) should be aligned with the beginning of the line {(opening curly brace)
    • * Curly braces should be used in all compound statements, even if there is only one statement, when they are part of the control structure, such as an if or a for statement. Doing so avoids the error caused when you add the statement later.

Marked

Statement marking is optional, only the following statements must be marked: while, Do,for,switch.

Return statement

A return statement with returned values does not use () (parentheses) to enclose the return value. If an expression is returned, the expression should be on the same line as the return keyword to avoid a semicolon error.

If statement

The IF statement should be in the following format:

  if (condition) {    statements;  }    if (condition) {    statements;}  else {    statements;  }    if (condition) {    Statements  } else if (condition) {    statements;}  else {    statements;  }

For statement

The For statement should be in the following format:

  for (initialization;condition update) {    statements  }  For (variable in object) if (filter) {    statements  }

The first form of the loop is used for an array loop that already knows the relevant parameters.

The second form is applied to the object. The members in the object prototype will be included in the iterator. It's a good idea to differentiate real object members by predefined hasOwnProperty methods:

  For (Variablein object) if (object.hasownproperty (variable)) {    statements;  }

While statement

The while statement should be in the following format:

  while (condition) {    Statements  }

Do statement

The do statement should be in the following format:

  do {    statements;  } while (condition);

Unlike other compound statements, a do statement always ends with A; (semicolon).

Switch statement

The switch statement should be in the following format:

  switch (expression) {case  expression:    statements;  Default:    statements;  }

Each case is aligned with the switch. This avoids excessive indentation.

Each group of statements (except default should end with Break,return, or throw). Don't let it go down in sequence.

Try Statement

The try statement should be in the following format:

  try {    statements  } catch (variable) {    statements  }  try {    statements  } catch (variable) {    statements;  } finally {    statements;  }

Continue statement

Avoid using continue statements. It is easy to make the logic of the program obscure and difficult to understand.

With statement

Do not use the WITH statement.

Blank

Using blank lines to separate logically related blocks of code can improve the readability of the program.

Spaces should be used in the following situations:

    • * The keywords following the ((left parenthesis) should be separated by a space. while (true) {
    • * There should be no spaces between the function arguments and ((opening parenthesis). This can help distinguish between keywords and function calls.
    • * All two-dollar operators, except. (points) and ((opening parenthesis) and [(left parenthesis) apply a space to separate it from the operand.
    • * There should be no space between the unary operator and its operands, unless the operator is a word, such as typeof.
    • * Each in the control section, for example in the For statement; (semicolon) to be followed by a space.
    • * each, (comma) should be followed by a space.

Another suggestion.

{} and []

Replace the new Object () with {}. Use [] instead of the new Array ().

Use an array to hold the data when the member name is a set of ordered numbers. Use objects to hold data when the member name is an irregular string or otherwise.

, (comma) operator

Avoid using the comma operator unless it is in the control section of a specific for statement. (This does not include comma separators that are used in object definitions, array definitions, VAR statements, and parameter lists.) )

Scope

There are no fields in the JavaScript block. Only functions have fields. Do not use blocks unless you are in a compound statement.

An assignment expression

Avoid assigning values in the conditional part of the IF and while statements.

  if (a = b) {

Is it a correct statement?

  if (a = = b) {

Is the right thing to do? Avoid this difficult to judge the right and wrong structure.

= = = and!== operator.

Using the = = = and!== operators is a relatively good point. the = = and!= operators perform type casts. In particular, do not use = = For comparison with error values (false,null,undefined, "", 0,nan).

Confusing Plus and minus signs

Be careful to follow + or + + after +. This form is easily still confusing. Parentheses should be inserted for easy understanding.

  Total = subtotal + +myinput.value;

Best to write

  Total = subtotal + (+myinput.value);

This + + will not be mistaken for + +.

Eval is a demon.

Eval is the easiest way to be abused in JavaScript. Avoid using it.

Eval has an alias. Do not use the function constructor. Do not pass string arguments to SetTimeout or setinterval.

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.