Erm, seems a good Javascript code standands.

Dojo Style Guide

Contents:

This document follows the basic outline of the Java Programming Conventions Guide, a copy of which may be found at http://geosoft.no/javastyle.html.

General

Any violation to this guide is allowed if it enhances readability.

Guidelines in this document are informed by discussions carried out among the Dojo core developers. The most weight has been given to considerations that impact external developer interaction with Dojo code and APIs. Rules such as whitespace placement are of a much lower order importance for Dojo developers, but should be followed in the main in order to improve developer coordination.

Quick Reference

Table of core API naming constructs:

ConstructConventionComment
modulelowercasenever multiple words
classCamelCase
public methodmixedCasewhether class or instance method. lower_case() is acceptable only if the particular function is mimicking another API.
public varmixedCase
constantCamelCase or UPPER_CASE

Table of constructs that are not visible in the API, and therefore carry less weight of enforcement.

ConstructConvention
private method_mixedCase
private var_mixedCase
method args_mixedCase, mixedCase
local vars_mixedCase, mixedCase

Naming Conventions

  1. Names representing modules SHOULD be in all lower case.

  2. Names representing types (classes) MUST be nouns and written using CamelCase capitalization:

    Account, EventHandler
  3. Constants SHOULD be placed within a single object created as a holder for constants, emulating an Enum; the enum SHOULD be named appropriately, and members SHOULD be named using either CamelCase or UPPER_CASE capitalization:

    var NodeTypes = {
            Element : 1,
            DOCUMENT: 2
    };
  4. Abbreviations and acronyms SHOULD NOT be UPPERCASE when used as a name:

    getInnerHtml ( ), getXml ( ), XmlDocument
  5. Names representing methods SHOULD be verbs or verb phrases:

    obj. getSomeValue ( )
  6. Public class variables MUST be written using mixedCase capitalization.

  7. CSS variable names SHOULD follow the same conventions as public class variables.

  8. Private class variables MAY be written using _mixedCase (with preceding underscore):

    var MyClass = function ( ) {
            var _buffer;
            this. doSomething = function ( ) {
            };
    }
  9. Variables that are intended to be private, but are not closure bound, SHOULD be prepended with a "_" (underscore) char:

    this._somePrivateVariable = statement;

    Note: the above variable also follows the convention for a private variable.

  10. Generic variables SHOULD have the same name as their type:

    setTopic (topic ) // where topic is of type Topic
  11. All names SHOULD be written in English.

  12. Variables with a large scope SHOULD have globally unambiguous names; ambiguity MAY be distinguished by module membership. Variables with small or private scope MAY have terse names.

  13. The name of the return object is implicit, and SHOULD be avoided in a method name:

    getHandler ( ); // NOT getEventHandler()
  14. Public names SHOULD be as clear as necessary and SHOULD avoid unclear shortenings and contractions:

    MouseEventHandler // NOT MseEvtHdlr

    Note that, again, any context that can be determined by module membership SHOULD be used when determining if a variable name is clear. For example, a class that represents a mouse event handler:

    dojo. events. mouse. Handler // NOT dojo.events.mouse.MouseEventHandler
  15. Classes/constructors MAY be named based on their inheritance pattern, with the base class to the right of the name:

    EventHandler
    UIEventHandler
    MouseEventHandler

    The base class CAN be dropped from a name if it is obviously implicit in the name:

    MouseEventHandler // as opposed to MouseUIEventHandler

Specific Naming Conventions

  1. The terms get/set SHOULD NOT used where a field is accessed, unless the variable being accessed is lexically private.

  2. The "is" prefix SHOULD be used for boolean variables and methods. Alternatives include "has", "can" and "should"

  3. The term "compute" CAN be used in methods where something is computed.

  4. The term "find" CAN be used in methods where something is looked up.

  5. The terms "initialize" or "init" CAN be used where an object or a concept is established.

  6. UI Control variables SHOULD be suffixed by the control type. Examples: leftComboBox, topScrollPane

  7. Plural form MUST be used to name collections.

  8. A "num" prefix or "count" postfix SHOULD be used for variables representing a number of objects.

  9. Iterator variables SHOULD be called "i", "j", "k", etc.

  10. Complement names MUST be used for complement entities. Examples: get/set, add/remove, create/destroy, start/stop, insert/delete, begin/end, etc.

  11. Abbreviations in names SHOULD be avoided.

  12. Negated boolean variable names MUST be avoided:

    isNotError, isNotFound are unacceptable.
  13. Exception classes SHOULD be suffixed with "Exception" or "Error" .. FIXME (trt) not sure about this?

  14. Methods returning an object MAY be named after what they return, and methods returning void after what they do.

Files

  1. Class or object-per-file guidelines are not yet determined.

  2. Tabs (set to 4 spaces) SHOULD be used for indentation.

  3. If your editor supports "file tags", please append the appropriate tag at the end of the file to enable others to effortlessly obey the correct indentation guidelines for that file:

    // vim:ts=4:noet:tw=0:
  4. The incompleteness of a split line MUST be made obvious :

    var someExpression = Expression1
            + Expression2
            + Expression3;
    var o = someObject. get (
            Expression1,
            Expression2,
            Expression3
    );

    Note the indentation for expression continuation is indented relative to the variable name, while indentation for parameters is relative to the method being called.

    Note also the position of the parenthesis in the method call; positioning SHOULD be similar to the use of block notation.

Variables

  1. Variables SHOULD be initialized where they are declared and they SHOULD be declared in the smallest scope possible. A null initialization is acceptable.
  2. Variables MUST never have a dual meaning.
  3. Related variables of the same type CAN be declared in a common statement; unrelated variables SHOULD NOT be declared in the same statement.
  4. Variables SHOULD be kept alive for as short a time as possible.
  5. Loops / iterative declarations
    1. Only loop control statements MUST be included in the "for" loop construction.
    2. Loop variables SHOULD be initialized immediately before the loop; loop variables in a "for" statement MAY be initialized in the "for" loop construction.
    3. The use of "do...while" loops is acceptable (unlike in Java).
    4. The use of "break" and "continue" is not discouraged (unlike in Java).
  6. Conditionals
    1. Complex conditional expressions SHOULD be avoided; use temporary boolean variables instead.
    2. The nominal case SHOULD be put in the "if" part and the exception in the "else" part of an "if" statement.
    3. Executable statements in conditionals MUST be avoided.
  7. Miscellaneous
    1. The use of magic numbers in the code SHOULD be avoided; they SHOULD be declared using named "constants" instead.
    2. Floating point constants SHOULD ALWAYS be written with decimal point and at least one decimal.
    3. Floating point constants SHOULD ALWAYS be written with a digit before the decimal point.

Layout

  1. Block statements.

    1. Block layout SHOULD BE as illustrated below:
      while (!isDone ) {
              doSomething ( );
              isDone = moreToDo ( );
      }
    2. if statements SHOULD have the following form:

      if (someCondition ) {
              statements;
      } else if (someOtherCondition ) {
              statements;
      } else {
              statements;
      }
    3. for statements SHOULD have the following form:

      for (initialization; condition; update ) {
              statements;
      }
    1. while statements SHOULD have the following form:

      while (!isDone ) {
              doSomething ( );
              isDone = moreToDo ( );
      }
    2. do...while statements SHOULD have the following form:

      do {
              statements;
      } while (condition );
    3. switch statements SHOULD have the following form:

      switch (condition ) {
      case ABC:
              statements;
              //  fallthrough
      case DEF:
              statements;
              break;
      default:
              statements;
              break;
      }
    4. try...catch...finallystatements SHOULD have the following form:

      try {
              statements;
      } catch (ex ) {
              statements;
      } finally {
              statements;
      }
    5. A single statement if-else, while or for MUST NOT be written without brackets, but CAN be written on the same line:

      if (condition ) { statement; }
      while (condition ) { statement; }
      for (intialization; condition; update ) { statement; }

Whitespace

  1. Conventional operators MAY be surrounded by a space (including ternary operators).
  2. The following reserved words SHOULD NOT be followed by a space:
    • break
    • catch
    • continue
    • do
    • else
    • finally
    • for
    • function if anonymous, ex. var foo = function(){};
    • if
    • return
    • switch
    • this
    • try
    • void
    • while
    • with
  3. The following reserved words SHOULD be followed by a space:
    • case
    • default
    • delete
    • function if named, ex. function foo(){};
    • in
    • instanceof
    • new
    • throw
    • typeof
    • var
  4. Commas SHOULD be followed by a space.
  5. Colons MAY be surrounded by a space.
  6. Semi-colons in for statements SHOULD be followed by a space.
  7. Semi-colons SHOULD NOT be preceded by a space.
  8. Function calls and method calls SHOULD NOT be followed by a space. Example: doSomething(someParameter); // NOT doSomething (someParameter)
  9. Logical units within a block SHOULD be separated by one blank line.
  10. Statements MAY be aligned wherever this enhances readability.

Comments

  1. Tricky code SHOULD not be commented, but rewritten.
  2. All comments SHOULD be written in English.
  3. Comments SHOULD be indented relative to their position in the code, preceding or to the right of the code in question.
  4. The declaration of collection variables SHOULD be followed by a comment stating the common type of the elements in the collection.
  5. Comments SHOULD be included to explain BLOCKS of code, to explain the point of the following block.
  6. Comments SHOULD NOT be included for every single line of code.

Documentation

Markup Guidelines

Using a Key

When parsing a comment block, we give the parser a list of "keys" to look for. These include summary, description, and returns, but many comment blocks will also have all of the variables and parameters in the object or function added to this list of keys as well.

If any of these keys occur at the beginning of a line, the parser will start reading the text following it and save it into the key until it find a blank line, or another key.

Using Markdown

The Markdown syntax is used in descriptions and code examples.

In Markdown, to indicate code, indent the code block using either four spaces, or a single tab. The parser considers the | (pipe) character to indicate the start of a line. You must use | followed by a tab or four spaces in order to indicate a code block.

General Information

These keys provide descriptions for the function or object:

  • summary: A short statement of the purpose of the function or object. Should be plain text.
  • description: An extended description of the function or object (uses Markdown)
  • returns: A description of what the function returns (does not include a type)
  • example: A writeup of an example. Uses Markdown syntax, so use Markdown syntax to indicate code blocks from any normal text. This key can occur multiple times.
General Function Information
function ( ) {
  // summary: Soon we will have enough treasure to rule all of New Jersey.
  // description: Or we could just get a new roommate.
  //        Look, you go find him.  He don't yell at you.
  //        All I ever try to do is make him smile and sing around
  //        him and dance around him and he just lays into me.
  //        He told me to get in the freezer 'cause there was a carnival in there.
  // returns:  Look, a Bananarama tape!
}
Object Information
Has no description of what it returns
var mcChris = {
  // summary: Dingle, engage the rainbow machine!
  // description:
  //        Tell you what, I wish I was--oh my g--that beam,
  //        coming up like that, the speed, you might wanna adjust that.
  //        It really did a number on my back, there. I mean, and I don't
  //        wanna say whiplash, just yet, cause that's a little too far,
  //        but, you're insured, right?
}
Function Assembler Information (defineWidget/declare)

If the declaration passes a constructor, the summary and description must be filled in there. If you do not pass a constructor, the comment block can be created in the passed mixins object.

For example:

dojo. declare (
  "steve",
  null,
  {
    // summary: Phew, this sure is relaxing, Frylock.
    // description:
    //    Thousands of years ago, before the dawn of
    //    man as we knew him, there was Sir Santa of Claus: an
    //    ape-like creature making crude and pointless toys out
    //    of dino-bones, hurling them at chimp-like creatures with
    //    crinkled hands regardless of how they behaved the
    //    previous year.
    // returns: Unless Carl pays tribute to the Elfin Elders in space.
  }
);

Parameters

Simple Types

Types should (but don't have to) appear in the main parameter definition block.

For example:

function ( /*String*/ foo, /*int*/ bar )...
Type Modifiers

There are some modifiers you can add after the type:

  • ? means optional
  • ... means the last parameter repeats indefinitely
  • [] means an array
function ( /*String?*/ foo, /*int...*/ bar, /*String[]?*/ baz )...
Full Parameter Summaries

If you want to also add a summary, you can do so in the initial comment block. If you've declared a type in the parameter definition, you do not need to redeclare it here.

The format for the general information is: *key *Descriptive sentence

The format for parameters and variables is: *key ~type~* Descriptive sentence

Where *key *and ~*type*~ can be surrounded by any non-alphanumeric characters.

function (foo, bar ) {
  // foo: String
  //        used for being the first parameter
  // bar: int
  //        used for being the second parameter
}

Variables

Instance variables, prototype variables and external variables can all be defined in the same way. There are many ways that a variable might get assigned to this function, and locating them all inside of the actual function they reference is the best way to not lose track of them, or accidentally comment them multiple times.
function foo ( ) {
  // myString: String
  // times: int
  //        How many times to print myString
  // separator: String
  //        What to print out in between myString*
  this. myString = "placeholder text";
  this. times = 5;
}
foo. prototype. setString = function (myString ) {
  this. myString = myString;
}
foo. prototype. toString = function ( ) {
  for (int i = 0; i < this. times; i++ ) {
    dojo. debug ( this. myString );
    dojo. debug (foo. separator );
  }
}
foo. separator = "=====";
Variable Comments in an Object
The parser takes the comments in between object values and applies the same rules as if they were in the initial comment block:
{
  // key: String
  //        A simple value
  key: "value",
  // key2: String
  //        Another simple value
}

Return Value

Because a function can return multiple types, the types should be declared on the same line as the return statement, and the comment must be the last thing on the line. If all the return types are the same, the parser uses that return type. If they're different, the function is considered to return "mixed".

function ( ) {
  if (arguments. length ) {
    return "You passed argument(s)"; // String
  } else {
    return false; // Boolean
  }
}

Documentation-Specific Code

Sometimes objects are constructed in a way that is hard to see from just looking through source. Or we might pass a generic object and want to let the user know what fields they can put in this object. In order to do this, there are two solutions:

Inline Commented-Out Code

There are some instances where you might want an object or function to appear in documentation, but not in Dojo, nor in your build. To do this, start a comment block with /*=====
. The number of = can be 5 or more.

The parser simply replaces the /*=====
and =====*/ with whitespace at the very start, so you must be very careful about your syntax.

dojo. mixin (wwwizard, {
/*=====
  // url: String
  //        The location of the file
  url: "",
  // mimeType: String
  //        text/html, text/xml, etc
  mimeType: "",
=====*/

  // somethingElse: Boolean
  //        Put something else here
  somethingElse: "eskimo"
} );
Code in a Separate File

Doing this allows us to see syntax highlighting in our text editor, and we can worry less about breaking the syntax of the file that's actually in the code-base during parsing. It's nothing more complicated that writing a normal JS file, with a dojo.provide call and everything.

It's a good idea to only have one of these per the namespace depth you're at. eg in the same directory that the file you're documenting is. We'll see an example of its use in the next section.

Documenting a kwArg

A lot of Dojo uses kwArg files. It's difficult to know how to use them sometimes. One option is to provide a pseudo-object describing its behavior. So we'll create module/_arg.js and do the following:

dojo. provide ( "module._arg" );
module._arg. myFuncArgs = function ( /*Object*/ kwArgs ) {
  // url: String
  //        Location of the thing to use
  // mimeType: String
  //        Mimetype to return data as
        this. url = kwArgs. url;
        this. mimeType = kwArgs. mimeType;
}

This describes a real object that mimics the functionality of the generic object you would normally pass, but also provides documentation of what fields it has and what they do.

To associate this object with the originating function, do this:

var myFunc = function ( /*module._arg.myFuncArgs*/ kwArgs ) {
  dojo. debug (kwArgs. url );
  dojo. debug (kwArgs. mimeType );
}

Since we didn't do a dojo.require on module._arg, it won't get included, but the documentation parser will still provide a link to it, allowing the user to see its functionality.

Which Documentation-Specific Syntax To Use

Documenting in another file reduces the chance that your code will break code parsing. It's a good idea from this perspective to use the separate file style as much as possible.

There are many situations where you can't do this, in which case you should use the inline-comment syntax. There is also a fear that people will forget to keep documentation in sync as they add new invisible mixed in fields. If this is a serious concern, you can also use the inline comment syntax.

Using the Doctool locally

If you are a developer who has marked their code up using this syntax and want to test to make sure it is correct, you can run the doctool yourself locally. See INSTALL in util/jsdoc. There is also a tool to quickly view simple parsing found in util/docscripts/_browse.php

转载于:https://www.cnblogs.com/winkingzhang/archive/2007/12/30/1020765.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值