在web项目开发过程中,为了是整个项目开发更加规范化、减少沟通成本和提高效率,对编码的规范还是很重要的一部分。以下就近期的项目经验,针对JavaScript的编码,做了如下的约定。
1、变量与声明:
1.1 声明前使用var 关键字
// bad
golobalVariable
// good
var globalVariable
1.2 变量声明中不能使用逗号分隔名一串变量
// bad
var items = getItems(),
goSportsTeam = true,
dragonball = 'z';
// good
var items = getItems();
var isGoSportsTeam = true;
var dragonball = 'z';
1.3 不要使用链式变量声明
// bad
var a = b = c =1;
//good
var a = 1;
var b = 1;
var c = 1;
1.2 变量在函数内部或者循环控制条件之前提前声明
// bad
function test() {
for(var i = 0; i < list.length; i++) {
var item = list[i];
}
}
//good
function test() {
var i;
var len = list.length;
var item;
for(i = 0; i < len; i++) {
item = list[i];
}
}
1.4 私有变量函数前置_标识
// bad
MyConstrctor.prototype.private = function() {};
// good
function _private() {}
MyConstructor.prototype._private = _private;
1.5 变量的命名规则最好是具象的,布尔值需要带 is, has, can, 单位值需要带 _ms, _s, _px 等
// bad
var height = $("#test").height();
var delay = 3 * 1000;
var readYet = true;
// good
var height_px = $("#test").height();
var delay_ms = 3 * 1000;
var isRead = true;
1.6 构造器首字母大写,方法变量要遵守驼峰命名规则
// bad
function generatortestpage() {};
generatortestpage.prototype.testpage = function() {};
// good
function GeneratorTestPage() {}
GeneratorTestPage.prototype.testPage = function() {};
2、常量
2.1 常量需要大写
2.2 常量需要定义在文件的头部,并使用_分割
// bad
var maxNumber = 13;
// good
var MAX_NUMBER = 13;
3、函数
3.1 函数内部不允许嵌套函数
3.2 函数内部不允许使用 arguments.callee 和 arguments.caller
3.3 函数参数不得超过5个参数(多于5个使用对象类型代替)
// bad
function testFunc(a,b,c,d,e,f,g,h) { }
// good
functiontestFunc(params) {
var a = params.a;
var b = params.b;
}
4、异常处理
4.1 允许使用 try/catch 语句,不能使用debugger、console、alert等关键字调试异常
5、循环
5.1 为了可读性,循环使用for,尽量避免使用while
5.2 出于性能考虑,在循环内不允许定义函数和变量
6、控制逻辑
6.1 判断的表达式必须放在“{}”中
// bad
if (5 = n) // ...
// good
if (5 == n) {
// do something...
}
6.2 控制流程语句中不能使用var 定义变量
6.3 分支超过5种判断使用 switch/case,在 switch/case 语句中必须带default
6.4 判断使用严格类型判断0、null、undefined, 固定字符使用 “===”
6.5 若判断条件过长,可以酌情换行或者用变量标识
// bad
if ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) {
thing1();
}
// good
if (
(foo === 123 || bar === 'abc') &&
doesItLookGoodWhenItBecomesThatLong() &&
isThisReallyHappening()
) {
thing1();
}
// good
var isType = (foo === 123 || bar === 'abc');
var hasTolong = doesItLookGoodWhenItBecomesThatLong();
var isHappend = isThisReallyHappening();
if(isType && hasTolong && isHappend) {}
7、字符串
7.1 允许使用多行字符串,使用“+” 或者 “\” 分割
// bad
var str = "<div><span><a href='#'>myhref</a></span></div>";
// good
var str = "<div>\
<span>\
<a href='#'>myhref</a>\
</span>\
</div>";
8、原型
8.1 禁止对Sring、Array 等原生对象进行原型修改
// bad
String.ptototype.preventChangePrototype = function() {}
// good
function preventChangePrototype() {}
8.2 由于子类会相互影响,原型上不允许保存属性,只能保存方法
9、注释
9.1 文件开头必须有文件说明注释,时间,作者
/*
* @Author: cxg
* @Date: 2017-09-16 21:04:07
* @Last Modified by: cxg
* @Last Modified time: 2017-09-25 14:03:52
* @fileOverview 本文件用于XXX,实现了XXX 方法, 注意事项XXX
*/
9.2 使用“/** ... */”进行多行注释
// bad
// make() returns a new element
// based on the passed in tag name
//
// @param {String} tag
// @return {Element} element
function make(tag) {
// ...
return element;
}
// good
/**
* make() returns a new element
* based on the passed-in tag name
*/
function make(tag) {
// ...
return element;
}
9.3 使用“//”单行注释。这个注释必须独占一行,若注释在块级作用域的第一行,注释前可以不用空一行,如果注释不在第一行,需要空一行在注释
// bad
const active = true; // is current tab
// good
// is current tab
const active = true;
// bad
function getType() {
console.log('fetching type...');
// set the default type to 'no type'
const type = this.type || 'no type';
return type;
}
// good
function getType() {
console.log('fetching type...');
// set the default type to 'no type'
const type = this.type || 'no type';
return type;
}
// also good
function getType() {
// set the default type to 'no type'
const type = this.type || 'no type';
return type;
}
9.4 在注释前加上 FIXME 和 TODO。FIXME:需要搞清楚这个问题,TODO:需要实现
class Calculator extends Abacus {
constructor() {
super();
// FIXME: 在这里不能设置为全局变量
total = 0;
}
}
class Calculator extends Abacus {
constructor() {
super();
// TODO: total 需要在 options 参数里配置
this.total = 0;
}
}
备注:对于分号和逗号的使用需要注意:
1、赋值、定义、返回值、方法调用后需要强制加分号
2、对象最后一个属性不要带逗号
网友评论