前端 JAVASCRIPT规范

目录

1.前言

制定良好的统一的JavaScript代码规范,提高代码质量和团队合作的效率。

2. 注释

  • As short as possible(如无必要,勿增注释):尽量提高代码本身的清晰性、可读性。
  • As long as necessary(如有必要,尽量详尽):合理的注释、空行排版等,可以让代码更易阅读、更具美感。
  • 函数/方法注释
    (1).函数/方法注释必须包含函数说明,有参数和返回值时必须使用注释标识;
    (2).参数和返回值注释必须包含类型信息和说明;
    (3).当函数是内部函数,外部不可访问时,可以使用 @inner 标识;
    /**
     * 函数描述
     *
     * @param {string} p1 参数1的说明
     * @param {string} p2 参数2的说明,比较长
     * 那就换行了.
     * @param {number=} p3 参数3的说明(可选)
     * @return {Object} 返回值描述
     **/
    function foo(p1, p2, p3) {
        var p3 = p3 || 10;
        return {
            p1: p1,
            p2: p2,
            p3: p3
        };
    }

3.缩进

缩进使用4个空格(四个空格在所有编辑器上显示缩进一致)

4.分号

4.1 在语句(Statement)的结尾加分号

    // bad
    (function() {
      var name = 'Skywalker'
      return name
    })()

    // good
    (function() {
      var name = 'Skywalker';
      return name;
    })();

4.2 这几种情况后需加分号:变量声明 表达式 return throw break continue do-while。

    /* 示例 */
    /* var declaration */
    var x = 1;

    /* expression statement */
    x++;

    /* do-while */
    do {
        x++;
    } while (x < 10);

5.逗号

行首不要出现逗号。

    // bad
    var demo = [
        app
      , icon
      , alive
    ];

    // good
    var demo = [
      app,
      icon,
      alive
    ];

6.引号

最外层统一使用单引号。

    // not good
    var x = "test";

    // good
    var y = 'foo',
    z = '<div id="test"></div>';

7.变量

7.1变量命名

  • 标准变量采用驼峰式命名(除了对象的属性外,主要是考虑到cgi返回的数据)
    //示例
    var thisIsMyName;
  • 'ID'在变量名中全大写
    //示例
    var thisID;
  • 'URL'在变量名中全大写
    //示例
    var reportURL;
  • 'Android'在变量名中大写第一个字母
    //示例
    var AndroidVersion;
  • 'iOS'在变量名中小写第一个,大写后两个字母
    //示例
    var iOSVersion;
  • 常量全大写,用下划线连接
    //示例
    var MAX_COUNT = 10;
  • jquery对象必须以'$'开头命名
    //not good
    var body = $('body');
    // good
    var $body=$('body');

7.2 变量声明

var 语句

  • 使用变量之前必须先定义,不要定义全局变量。
    //bad
    count = 10; //严格模式中报错
    console.log(global.count); //10

    //good
    var count = 10;
  • 使用 var 声明每一个变量。
    这样做的好处是增加新变量将变的更加容易,而且你永远不用再担心调换错分号跟逗号。
    // not good
    var uname,
        uid,
        upwd;
    //good  
    var uname;
    var uid='';
    var upwd='';

8.对象

  • 使用字面值创建对象
    // bad
    var test = new Object();

    // good
    var test = {};
    // bad
    var superman = {
      class: 'superhero',
      default: { clark: 'kent' },
      private: true
    };

    // good
    var superman = {
      klass: 'superhero',
      defaults: { clark: 'kent' },
      hidden: true
    };

9.数组

  • 使用字面值创建数组
    // bad
    var items = new Array();

    // good
    var items = [];
  • 向数组增加元素时使用 Array#push 来替代直接赋值。
    var arrayList = [];
    // bad
    arrayList[arrayList.length] = '111111';

    // good
    arrayList.push('1111111');
  • 当你需要拷贝数组时,使用 Array#slice。参见jsperf
    var len = items.length;
    var itemsCopy = [];
    var i;

    // bad
    for (i = 0; i < len; i++) {
      itemsCopy[i] = items[i];
    }

    // good
    itemsCopy = items.slice();

10.字符串

  • 使用单引号 '' 包裹字符串。
    // bad
    var test = "sakjas";

    // good
    var test = 'adas dasdas';
  • 超过 100 个字符的字符串应该使用连接符写成多行。 但是,如果过度使用,通过连接符连接的长字符串可能会影响性能。jsPerf & 讨论.
    // bad
    var 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.';

    // bad
    var 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.';

    // good
    var 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.';

11.比较运算符 和 等号

  • 优先使用 === 和 !== 而不是 == 和 !=. 使用 === 可以避免等于判断中隐式的类型转换。
    // bad
    if (number == 10) {
        // ......
    }

    // good
    if (number === 10) {
        // ......
    }  
  • 条件表达式例如 if 语句通过抽象方法 ToBoolean 强制计算它们的表达式并且总是遵守下面的规则: 1.对象 被计算为 true 2.Undefined 被计算为 false 3.Null 被计算为 false 4.布尔值 被计算为 布尔的值 5.数字 如果是 +0、-0 或 NaN 被计算为 false,否则为 true 6.字符串 如果是空字符串 '' 被计算为 false,否则为 true

  • 尽量使用简介的表达方式.

    // bad  
    if (name !== '') {  
      // 字符串是否为空
    }

    // good  
    if (name) {  
      // 字符串是否为空
    }

    // bad  
    if (collection.length > 0) {  
      // 数组是否为空  
    }

    // good  
    if (collection.length) {  
      // 数组是否为空  
    }  

了解更多信息在 Truth Equality and JavaScript by Angus Croll.

12.类型转换

  • 字符串:
    //  => this.num = 2;  

    // bad  
    var total = this.num + '';  

    // good  
    var total = '' + this.num;  

    // bad  
    var total = '' + this.num + ' total score';  

    // good  
    var total = this.num + ' total score';    
  • 使用 parseInt 转换数字时总是带上类型转换的基数。
    var inputValue = '4';  

    // bad  
    var val = new Number(inputValue);  

    // bad  
    var val = +inputValue;  
    // bad  
    var val = parseInt(inputValue);  

    // good  
    var val = Number(inputValue);  

    // good 
    var val = parseInt(inputValue, 10);  
  • 转换成布尔类型:
    var page = 0;  

    // bad  
    var tpage = new Boolean(page);

    // good
    var tpage = Boolean(page);  

    // good    
    var tpage = !!page;  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容