Javascript代码规范
JMFE Javascript代码规范v1.0。抛砖引玉,请大家多给建议,多做补充。定稿后组内使用统一Linter配置。

命名规范
变量
避免单字母名称,让名称具有描述性
123456789// goodfunction query() {// ...}// badfunction q() {// ...}使用驼峰写法
12345678// goodvar thisIsMyObj = {};function thisIsMyFun() {}// badvar OBJEcttsssss = {};var this_is_my_object = {};function c() {}多词相连时,>=6个字母的词使用缩写
12345678// goodvar people = {};var compListTpl = [];function fmtDate() {};// badvar componentListTemplate = [];var formatDate() {};
私有属性
- 封装私有属性时使用
_前缀123456789// goodfunction people(name) {var _ageMap = {"张三" : "21","小红" : "20"}this.name = name;this.age = _ageMap[name];}
this
- 保存this引用时使用self1234567891011121314151617181920212223// goodfunction() {var self = this;return function() {console.log(self);};}// badfunction() {var that = this;return function() {console.log(that);};}// badfunction() {var _this = this;return function() {console.log(_this);};}
jQuery变量
- jQuery对象变量使用
$前缀12345// goodvar $sidebar = $('.sidebar');// badvar sidebar = $('.sidebar');
文件名
- 如果文件作为一个依赖被导出,文件名和导出名保持一致12345678910111213141516// file contentsclass CheckBox {// ...}module.exports = CheckBox;var CheckBox = require('./CheckBox');// goodvar CheckBox = require('./CheckBox');// badvar CheckBox = require('./checkBox');// badvar CheckBox = require('./check_box');
语句规范
空格 缩进
缩进使用tab设置四个空格
1234567891011121314// goodfunction() {∙∙∙∙var name;}// badfunction() {var name;}// badfunction() {∙∙var name;}对象声明格式
123456789101112131415161718192021222324252627282930// goodvar coder = {name : "张三",age : 21,girlFreind : {name : "小红",age : 20}};// badvar coder = {name : "张三",age : 21,girlFreind : {name : "小红",age : 20}};// badvar coder ={name : "张三",age : 21,girlFreind : {name : "小红",age : 20}};// badvar coder={name:"张三",age:21,girlFreind:{name:"小红",age:20}};函数声明格式
123456789101112// goodfunction test() {console.log('test');}// badfunction test (){console.log('test');}// badfunction test (){console.log('test');}用空白分隔运算符
12345// goodvar x = y + 5;// badvar x=y+5;if、while语句块
12345678910111213141516171819202122232425262728293031// goodif () {// ...// ...} else {// ...// ...}// badif () {// ...// ...}else {// ...// ...}// goodif () // ...else // ...// badif (){ console.log("one line"); }else{ console.log("one line"); }// goodwhile () {// ...}switch语句块
12345678switch () {case "1":// ...break;case "2":// ...break;}
运算符
- 使用快捷方式计算布尔值12345678910111213141516171819// goodif (name) {// ...}// badif (name !== '') {// ...}// goodif (collection.length) {// ...}// badif (collection.length > 0) {// ...}
创建变量
基本规则
使用var声明每个变量,结构整洁,并且容易添加新的变量声明,而不用去担心多用
;123456789101112131415// goodvar items = getItems();var name = "张三";var age = 21;// badvar items = getItems(),name = "张三",age = 21;// bad// (compare to above, and try to spot the mistake)var items = getItems(),name = "张三";age = 21;在作用域顶部一次性声明所有变量,并最后声明未赋值的变量
123456789101112131415161718// goodvar items = getItems();var name;var age;var sex;//...name = "张三";//...age = 21;sex = "male";// badvar items = getItems();//...var name = "张三";//...var age = 21;var sex = "male";
对象
- 使用字面量创建对象12345// goodvar item = {};// badvar item = new Object();
数组
使用字面量创建数组
12345// goodvar item = [];// badvar items = new Array();添加删除数组元素时,使用push、pop、unshift、shift,不直接操作数组元素
1234567var someStack = [];// goodsomeStack.push('aaa');// badsomeStack[someStack.length] = 'aaa';
字符串
使用双引号包裹字符串
12345// goodvar name = "张三";// badvar name = '张三';超过80个字符的字符串使用字符串连接符进行换行
12345678910111213// goodvar errorMessage = 'This is a super long error that was thrown because ' +'of Batman. When you stop to think about how Batman had anything to do ' +'with this, you would get nowhere fast.';// badvar errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';// badvar errorMessage = 'This is a super long error that was thrown because \of Batman. When you stop to think about how Batman had anything to do \with this, you would get nowhere \fast.';以编程方式创建字符串时使用Array的join方法而不是通过连接符
123456789101112131415161718192021222324252627282930313233343536373839var items;var messages;var length;var i;messages = [{state: 'success',message: 'This one worked.'}, {state: 'success',message: 'This one worked as well.'}, {state: 'error',message: 'This one did not work.'}];length = messages.length;// goodfunction inbox(messages) {items = [];for (i = 0; i < length; i++) {items.push('<li>' + messages[i].message + '</li>');}return '<ul>' + items.join('') + '</ul>';}// badfunction inbox(messages) {items = '<ul>';for (i = 0; i < length; i++) {items += '<li>' + messages[i].message + '</li>';}return items + '</ul>';}
注释
单行
- 单行注释使用
//,注释符后空一格,把单行注释放在语句的上一行,并且在注释之前空一行12345678910111213141516171819202122232425// good// is current tabvar active = true;// badvar active = true; // is current tab// goodfunction getType() {console.log('fetching type...');// set the default type to 'no type'var type = this._type || 'no type';return type;}// badfunction getType() {console.log('fetching type...');//set the default type to 'no type'var type = this._type || 'no type';return type;}
多行
- 多行注释使用
/* */,注释符前后换行,缩进4格开始写注释123456789101112131415// good/*this is anannotation example*/var active = true;// bad/* this is an annotation example */var active = true;// bad// this is an// annotation examplevar active = true;
方法注释
- 注明方法作用、入参类型和说明、返回类型和说明123456789/*** 格式化金额 1234567.890 -> 1,234,568 || 1234567.9 | 1234567.89 | 1234567.8900* @param {anytype} str 待格式化数字,可为任何类型 传入非数字时直接返回* @param {[Number | String]} fixedNum 四舍五入几位,取值0-20,可不传,小数默认截取两位* @return {String} 格式化后的数字,String类型*/function splitMoney(str, fixedNum) {// ...}
Author: Kasim
Origin: http://kaxium.github.io
Link: http://kaxium.github.io/2016/06/06/代码规范/
本文采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可