File Organization

  • All javascript files should be placed in the project's common '''script''' folder
  • Third-party library files used should be placed in the '''script/lib''' folder
  • Reusable custom modules should be placed in the '''script/commons''' folder. If a reusable module involves multiple sub-files, a separate module folder needs to be created
  • Javascript files used by individual page modules should be placed in the '''script/{module_name}''' folder
  • JSON data simulated by the project should be placed in the '''script/json''' folder, with separate sub-folders created per page
  • When using an MVC framework in JavaScript, the template files used should be placed in the '''script/templates''' folder, with separate sub-folders created per page

Formatting

  • General principles can refer to [PhpGuideline PHP Coding Standards]
  • Always use var to define variables
var global = '';

function method() {
    var local = '';
}
  • Always end a declaration statement with a semicolon
  • Do not use extra "," for arrays and objects (for IE compatibility)
//wrong
var arr = [1,2,];
var person = {
    name: 'name',
    age: 20,
};
//wrong
var arr = [1,2];
var person = {
    name: 'name',
    age: 20
};
  • Define a top-level namespace such as inBike, and define custom private namespaces under the top-level namespace, divided according to modules
  • All module code should be placed in anonymous self-invoking functions, exposed by assigning values to custom namespaces under the window object
if (!window.inBike) {
    window.inBike = {};
}
window.inBike.rideway = rideway;
  • Event binding code needs to be executed in the DOM ready function
$(function() {
     //bind function is in the init function
     window.inBike.rideway.init();
})
  • Place custom module methods in an object. The method name should be immediately followed by ":". Leave one space between ":" and "function". Leave one space between "function()" and the following "{"
var module = function() {
    method: function() {

    }
};
  • Use single quotes to wrap strings
var str = 'some text';
  • All variables used need to be defined before use, and initialized immediately after definition
var obj = null;
var num = 0;
var arr = [];
var isEmpty = true;
  • Check whether it is supported before using the browser console tool
if (console) {
    console.log('this is my log');
}

Naming

  • General principles can refer to [PhpGuideline PHP Coding Standards]
  • Use camelCase to name variables and method names, with the first letter lowercase. For class names, the first letter should be uppercase
var numberList = [1,2];
var util = {
    removeNode: function(){
        ....
    }
};

function Person(name, age) {
    this.name = name;
    this.age = age;
}
  • Use $name to name jQuery objects. Native DOM elements start with "dom". Private variables in an object start with an underscore
var $image = $('#cover');
var domImage = document.getElementById('cover');
var obj = {
    _privateVar: null,
    method: function() {

    }
};

Comments

  • General principles can refer to [PhpGuideline PHP Coding Standards]
  • Use more single-line comments to indicate the meaning of logic blocks
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
    return rootjQuery.find( selector );
}

// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
  • Indicate the constructor method of the class
/**
 * @constructor
 */
some.long.namespace.MyClass = function() {
};
  • Annotate the type and meaning of enum constants
/** @enum {string} */
some.long.namespace.Fruit = {
  APPLE: 'a',
  BANANA: 'b'
};
  • Use comments to mark the visibility of methods or variables, making static checking easier
/** @protected */
AA_PublicClass.staticProtectedProp = 31;

/** @private */
AA_PublicClass.prototype.privateMethod_ = function() {};

Best Practices

  • Avoid using eval
  • Avoid using with for objects, and avoid using for-in for arrays
  • Use closures cautiously to avoid circular references
  • Be wary of the context in which this is used
var $button = $('#my-button');
$button.click(function(){
    var self = this;
    var util = {
       getVal: function() {
           return self.val();
       }
    }
});
  • Use shorthand as much as possible, such as ternary operators, logical switching, increment operations, etc.
var name = ('undefined' == typeof(name)) ? '' : name;
(age < 0) && (age = 0);
count++;
  • Do not use function in block-level scope
// 错误
if (x) {
  function foo() {}
}

// 正确
if (x) {
  var foo = function() {}
}
  • Bind event listeners on the parent node and respond separately based on the event source
  • For complex page modules, use dependency management libraries such as SeaJS, RequireJS, and MVC frameworks like Backbone, Knockout, Stapes to organize your code