JavaScript Conventions

With any program design it is important to use a programming convention when writing code. This not only helps the code look consistent (and one hopes avoids certain bugs), but also allows different programmers to work on the same code.

The Alt Framework is no exception, so I hope to outline the conventions I am using throughout the project for JavaScript. (I am using the standard Java coding conventions for the Java code).

These conventions are guidelines, but not requirements, preferably all the rules should be met, but there are cases when there is good sense to break the convention.

File/Module Structure

AltServlet provides a certain degree of organization with its module system, but I will go a few steps further to say that:

  1. Each class should be in its own file of the same name, and should be within a descriptive package. For example, the SQLSchema class is in the alt.squeal package, and thus can be found in the file alt/squeal/SQLSchema.js.
  2. Scripts should require only the fewest number of scripts as necessary.
  3. The wildcard module require should not be used. (I.E. Alt.require("alt.*").)

Syntax

Syntax conventions are written similar to the Java conventions:

  1. 4-space soft-tabs (or hard-tabs)
  2. Optional semi-colons should always be included.
  3. Open curly braces should be on the same line as their statement (such as, if, while, for, etc.).
  4. Optional curly braces around single-statement blocks should be left out (if, while, for, but not switch, try, or catch). If an if statement is combined with one or more else statements and one of the blocks has curly braces, then all the blocks should have curly braces (even if they're optional).
  5. White space should be used generously to separate ideas and make code more readable.

Style

JavaScript is powerful because it offers a number of ways to do things.

  1. Anonymous functions should not be named. ("arguments.callee" can be used for recursive calls in anonymous functions.)
  2. Avoid global functions if an inner function is sufficient.
  3. Always use var for local variables.
  4. Use comments to describe any complex bit of code, especially in long functions.
  5. Always put jsdocs on functions, even if they are considered "private." Try to document all parameters, exceptions, and return values.
  6. Classes should be defined with the standard named function syntax whenever possible (instead of assigning anonymous functions to variables).
  7. Class functions, on the other hand, should be defined as members of the prototype object with the anonymous function syntax.
  8. Class inheritance is defined by: SubClass.prototype = new BaseClass;
  9. Super class constructors can (and should) be called with the Function.call method.

copy from:http://alt.cellosoft.com/js-conventions.html

 

 See http://www.cnitblog.com/alsan/articles/8069.html for more information.

 

posted on 2012-02-26 22:03  Jalen Wang  阅读(257)  评论(0编辑  收藏  举报

导航