命名规则
- 方法 - 驼峰形式,首字母小写
function getName() {
return 'Mark';
}
- 类 - 驼峰形式,首字母大写
// 正确的写法
var FooAndToo = function(name) {
this.name = name;
}
- 变量 - 全小写,‘_’分隔单词。另一种规范是以采用和function一致的命名规则。
var my_name = 'Mark';
- 常量 - 全大写,‘_’分隔单词
const ISSUE_COUNT = 100;
- 对象属性, 基本类型:变量,function:方法
var data = {
his_name: 'Joe',
getName: function() {
return 'Joe';
}
}
编码规范
- 行尾必须有结束符
;
- 使用4空格的tab缩进代码
- 代码注释应在行代码后面,块代码上面
- 代码块前必须有一个空行
if (wl && wl.length) {
for (i = 0, l = wl.length; i < l; ++i) {
p = wl[i];
type = Y.Lang.type(r[p]);
if (s.hasOwnProperty(p)) {
// 处理merge逻辑
if (merge && type == 'object') {
Y.mix(r[p], s[p]);
} else if (ov || !(p in r)) {
r[p] = s[p];
}
}
}
}
-
this缓存应使用that,self,_this,me, 不应使用其他名称
-
局部变量应在首部定义
-
块内函数必须用局部变量声明
var call = function(name) {
var foo;
if (name == "hotel") {
foo = function() {
console.log("hotel foo");
}
}
foo && foo();
}
- 推荐使用function实现类, 不推荐使用继承
//1. function 类的实现
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function() {
alert(this.name);
};
var me = new Person("Nicholas");
// 将this放到局部变量self
function Persion(name, sex) {
var self = this;
self.name = name;
self.sex = sex;
}
//2. 继承实现类
function A(){
//...
}
function B(){
//...
}
B.prototype = new A();
B.prototype.constructor = B; //原则上,记得把这句话加上