前端 JAVASCRIPT規(guī)范

目錄

1.前言

制定良好的統(tǒng)一的JavaScript代碼規(guī)范,提高代碼質(zhì)量和團(tuán)隊(duì)合作的效率。

2. 注釋

  • As short as possible(如無必要,勿增注釋):盡量提高代碼本身的清晰性、可讀性。
  • As long as necessary(如有必要,盡量詳盡):合理的注釋、空行排版等,可以讓代碼更易閱讀、更具美感。
  • 函數(shù)/方法注釋
    (1).函數(shù)/方法注釋必須包含函數(shù)說明,有參數(shù)和返回值時(shí)必須使用注釋標(biāo)識(shí);
    (2).參數(shù)和返回值注釋必須包含類型信息和說明;
    (3).當(dāng)函數(shù)是內(nèi)部函數(shù),外部不可訪問時(shí),可以使用 @inner 標(biāo)識(shí);
    /**
     * 函數(shù)描述
     *
     * @param {string} p1 參數(shù)1的說明
     * @param {string} p2 參數(shù)2的說明,比較長
     * 那就換行了.
     * @param {number=} p3 參數(shù)3的說明(可選)
     * @return {Object} 返回值描述
     **/
    function foo(p1, p2, p3) {
        var p3 = p3 || 10;
        return {
            p1: p1,
            p2: p2,
            p3: p3
        };
    }

3.縮進(jìn)

縮進(jìn)使用4個(gè)空格(四個(gè)空格在所有編輯器上顯示縮進(jìn)一致)

4.分號(hào)

4.1 在語句(Statement)的結(jié)尾加分號(hào)

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

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

4.2 這幾種情況后需加分號(hào):變量聲明 表達(dá)式 return throw break continue do-while。

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

    /* expression statement */
    x++;

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

5.逗號(hào)

行首不要出現(xiàn)逗號(hào)。

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

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

6.引號(hào)

最外層統(tǒng)一使用單引號(hào)。

    // not good
    var x = "test";

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

7.變量

7.1變量命名

  • 標(biāo)準(zhǔn)變量采用駝峰式命名(除了對(duì)象的屬性外,主要是考慮到cgi返回的數(shù)據(jù))
    //示例
    var thisIsMyName;
  • 'ID'在變量名中全大寫
    //示例
    var thisID;
  • 'URL'在變量名中全大寫
    //示例
    var reportURL;
  • 'Android'在變量名中大寫第一個(gè)字母
    //示例
    var AndroidVersion;
  • 'iOS'在變量名中小寫第一個(gè),大寫后兩個(gè)字母
    //示例
    var iOSVersion;
  • 常量全大寫,用下劃線連接
    //示例
    var MAX_COUNT = 10;
  • jquery對(duì)象必須以'$'開頭命名
    //not good
    var body = $('body');
    // good
    var $body=$('body');

7.2 變量聲明

var 語句

  • 使用變量之前必須先定義,不要定義全局變量。
    //bad
    count = 10; //嚴(yán)格模式中報(bào)錯(cuò)
    console.log(global.count); //10

    //good
    var count = 10;
  • 使用 var 聲明每一個(gè)變量。
    這樣做的好處是增加新變量將變的更加容易,而且你永遠(yuǎn)不用再擔(dān)心調(diào)換錯(cuò)分號(hào)跟逗號(hào)。
    // not good
    var uname,
        uid,
        upwd;
    //good  
    var uname;
    var uid='';
    var upwd='';

8.對(duì)象

  • 使用字面值創(chuàng)建對(duì)象
    // 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.數(shù)組

  • 使用字面值創(chuàng)建數(shù)組
    // bad
    var items = new Array();

    // good
    var items = [];
  • 向數(shù)組增加元素時(shí)使用 Array#push 來替代直接賦值。
    var arrayList = [];
    // bad
    arrayList[arrayList.length] = '111111';

    // good
    arrayList.push('1111111');
  • 當(dāng)你需要拷貝數(shù)組時(shí),使用 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.字符串

  • 使用單引號(hào) '' 包裹字符串。
    // bad
    var test = "sakjas";

    // good
    var test = 'adas dasdas';
  • 超過 100 個(gè)字符的字符串應(yīng)該使用連接符寫成多行。 但是,如果過度使用,通過連接符連接的長字符串可能會(huì)影響性能。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.比較運(yùn)算符 和 等號(hào)

  • 優(yōu)先使用 === 和 !== 而不是 == 和 !=. 使用 === 可以避免等于判斷中隱式的類型轉(zhuǎn)換。
    // bad
    if (number == 10) {
        // ......
    }

    // good
    if (number === 10) {
        // ......
    }  
  • 條件表達(dá)式例如 if 語句通過抽象方法 ToBoolean 強(qiáng)制計(jì)算它們的表達(dá)式并且總是遵守下面的規(guī)則: 1.對(duì)象 被計(jì)算為 true 2.Undefined 被計(jì)算為 false 3.Null 被計(jì)算為 false 4.布爾值 被計(jì)算為 布爾的值 5.數(shù)字 如果是 +0、-0 或 NaN 被計(jì)算為 false,否則為 true 6.字符串 如果是空字符串 '' 被計(jì)算為 false,否則為 true

  • 盡量使用簡(jiǎn)介的表達(dá)方式.

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

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

    // bad  
    if (collection.length > 0) {  
      // 數(shù)組是否為空  
    }

    // good  
    if (collection.length) {  
      // 數(shù)組是否為空  
    }  

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

12.類型轉(zhuǎn)換

  • 字符串:
    //  => 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 轉(zhuǎn)換數(shù)字時(shí)總是帶上類型轉(zhuǎn)換的基數(shù)。
    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);  
  • 轉(zhuǎn)換成布爾類型:
    var page = 0;  

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

    // good
    var tpage = Boolean(page);  

    // good    
    var tpage = !!page;  
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容