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 类型的变量使用 is 或 has 开头。
示例:
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();