JavaScript编码规范

1代码风格

1.1结构语句

[强制]不得省略语句结束的分号。

[强制]if / else / for / do / while语句中,即使只有一行,也不得省略块{...}

示例:

// good
if (condition) {
    callFunc();
}

// bad
if (condition) callFunc();
if (condition)
    callFunc();

1.2命名

[强制]变量使用Camel命名法

示例:

var loadingModules = {};

[强制]常量使用全部字母大写,单词间下划线分隔的命名方式。

示例:

var HTML_ENTITY = {};

[强制]函数使用Camel命名法

示例:

function stringFormat(source) {

}

[强制]函数的参数使用Camel命名法

示例:

function hear(theBells) {

}

[强制]使用Pascal命名法

示例:

function TextNode(options) {

}

[强制]类的方法/属性使用Camel命名法

示例:

function TextNode(value, engine) {
    this.value = value;
    this.engine = engine;
}

TextNode.prototype.clone = function () {
    return this;
};

[强制]枚举变量使用Pascal命名法枚举的属性使用全部字母大写,单词间下划线分隔的命名方式。

示例:

var TargetState = {
    READING: 1,
    READED: 2,
    APPLIED: 3,
    READY: 4
};

[强制]命名空间使用Camel命名法

示例:

equipments.heavyWeapons = {};

[强制]由多个单词组成的缩写词,在命名中,根据当前命名法和出现的位置,所有字母的大小写与首字母的大小写保持一致。

示例:

function XMLParser() {

}

function insertHTML(element, html) {

}

var httpRequest = new HTTPRequest();

[强制]类名使用名词

示例:

function Engine(options) {

}

[建议]函数名使用动宾短语

示例:

function getStyle(element) {

}

[建议]boolean类型的变量使用ishas开头。

示例:

var isReady = false;
var hasMoreCommands = false;

2语言特性

2.1变量

[强制]变量在使用前必须通过var定义。

解释:

不通过 var 定义变量将导致变量污染全局环境。

示例:

// good
var name = 'MyName';

// bad
name = 'MyName';

2.2面向对象

[强制]创建对象使用构造函数模式和原型模式组合方式。

示例:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.sayName = function () {
    alert(this.name);
};

var person1 = new Person('Tom', 29);
var person2 = new Person('Greg', 27);
person1.sayName();
alert(person2.age);

[强制]类的继承使用寄生组合式继承。

示例:

function inheritPrototype(subType, superType) {
    function F() {}
    F.prototype = superType.prototype;
    var prototype = new F();
    prototype.constructor = subType;
    subType.prototype = prototype;
}

function SuperType(name) {
    this.name = name;
    this.colors = ['red', 'blue', 'green'];
}

SuperType.prototype.sayName = function() {
    console.log(this.name);
};

function SubType(name, age) {
    SuperType.call(this, name);
    this.age = age;
}
inheritPrototype(SubType, SuperType); SubType.prototype.sayAge = function() { console.log(this.age); }; var instance1 = new SubType('Nicholas', 29); instance1.colors.push('black'); console.log(instance1.colors); instance1.sayName(); instance1.sayAge(); var instance2 = new SubType('Greg', 27); console.log(instance2.colors); instance2.sayName(); instance2.sayAge();