Bootstrap

Node 编码规范 -努力做得更好

1. 缩进

  • 统一两个空格缩进

1.变量

  • 变量命名采用小驼峰命名,如:addUser password studentID

2.常量

  • 常量命名采用单词所有字母大写,并用下划线分隔,如:FORM_NAME

3.方法

  • 对于对象、函数、和实例采用小驼峰(camelCase)命名法

  • 类方法:methodNamesLikeThis

// 对象
let isObject = {};
// 函数
function isFun(){
 ...
};
// 实例
let myBbj = new Object();

4.类&枚举

  • 对于类命名或者构造函数,采用大驼峰命名 User() DateBase()

  • 枚举类型:ClassNamesLikeThis, EnumNamesLikeThis,

// 类
class Point {
  ...
};

// 构造函数
function User(options) {
  this.name = options.name;
}

let myBbj = new User({
  name: 'yup'
});

5.文件

  • 单词之间使用 ‘’ underscore 来 分割,如果你不想暴露某个文件给用户 , 你也可以用‘’ 来开头

child_process.js
string_decoder.js
_linklist.js

6.包

7. 空格

操作符与操作算子之间要有空格

var string = 'Foo' + bar;  // good

var string = 'Foo'+bar;  //bad

8. 单引号

使用 string 时,用单引号替代双引号(写JSON 时除外)

// good
var foo = 'bar';
var http = require('http');

// bad

var foo = "bar";
var http = require("http");

9.比较操作

有的场景下应该用 "===" 替代 "==" 当你遇到这些符号比较时 :0 undefined null false true你应该小心谨慎 比如 ' \t\r\n' == 0 比较结果是 true

// good
var a = 0;
if (a === '') {
  console.log('winning');
}

// bad
var a = 0;
if (a == '') {
  console.log('losing');
}

10. Requires

  • 建议使用以下顺序来组织 node 代码中的 require 代码

var http = require('http');
var fs = require('fs');
var async = require('async');
var mongoose = require('mongoose');
var Car = require('./service/user');

  • 引入模块时,不要加 .js 后缀

var Batmobil = require('./service/user');

11. 字面表达式

  • 用 '{}' ,'[]' 代替 new Array ,new Object

  • 不要使用 string,bool,number 的对象类型,即不要调用 new String ,new Boolean ,new Number

  • 避免使用 “with” 与 “eval”

  • for-in 循环,仅在 object/hash/map 时使用,绝不要对Array 使用

  • 不要把Array 当做关联数组或Object 使用,即你不应该用非数字作为Array 的索引

// bad
var a = []; // use '{}' instead
a['hello'] = 'shit';
a['foo'] = 'bar';

// good
var a = {};
a.hello = 'shit';
a.foo = 'bar';

12. 私有变量

  • exports 一个类,对于此类的私有成员变量,建议加上 "_" 前缀以示区分

13. 避免魔鬼数字的出现

魔鬼数字主要指在代码中没有具体含义的数字、字符串。影响了代码可读性,读者看到的数字无法理解其含义,从而难以理解程序的意图。当程序中出现的魔鬼数字过多时,代码的可维护性将会急剧下降,代码变得难以修改,并容易引入错误。

// 接口成功返回的标识
const SUCCESS_CODE = 1;
// 接口失败返回的标识
const FAIL_CODE = 0;

14. 注释

/**
 * make() returns a new element
 * based on the passed in tag name
 * @param  tag
 * @return  element
 */

// 单行注释