fidding編碼規(guī)范之JS篇

良好的編程規(guī)范是打造優(yōu)秀代碼的基礎(chǔ),以下是fidding個人編碼規(guī)范整理度硝,使用ECMAScript 6.0(ES6)標(biāo)準(zhǔn)肿轨,并借鑒了許多文章與書籍的優(yōu)秀編碼習(xí)慣,本人也將持續(xù)更新與改進蕊程。

變量與常量

  1. 使用const定義常量
// bad
var foo = 1;
// good
const foo = 1;
  1. 使用let替代var
// bad
var foo = 1;
// good
let foo = 1;

對象Object

  1. 使用{}直接創(chuàng)建對象
// bad
const object = new Object();
// good
const object = {};
  1. 鍵名移除多余的''""符號
// bad
const bad = {
        'foo': 3,
        'bar': 4,
        'data-blah': 5
};
// good
const good = {
        foo: 3,
        bar: 4,
        'data-blah': 5
};

數(shù)組Array

  1. 使用[]直接創(chuàng)建數(shù)組
// bad
const array = new Array();
// good
const array = [];
  1. 使用push添加數(shù)組項
const array = [];
// bad
array[array.length] = 'abc';
// good
array.push('abc');
  1. 使用數(shù)組展開符...拷貝數(shù)組
// bad
const len = array.length;
const arrayCopy = [];
let i;
for (i = 0; i < len; i++) {
        arrayCopy[i] = array[i];
}
// good
const arrayCopy = [...array];

字符串String

  1. 使用單引號替代雙引號''
// bad
const string = "Hong. Jiahuang";
// good
const string = 'Hong. Jiahuang';
  1. 盡可能使用模版代替字符串串聯(lián)拼接
// bad
function sayHi(name) {
        return 'How are you, ' + name + '?';
}
// bad
function sayHi(name) {
        return ['How are you, ', name, '?'].join();
}
// bad
function sayHi(name) {
        return `How are you, ${ name }?`;
}
// good
function sayHi(name) {
        return `How are you, ${name}?`;
}
  1. 拒絕使用eval()來解析字符串椒袍,會造成很多安全問題。

函數(shù)Function

  1. 當(dāng)需要立即調(diào)用函數(shù)時藻茂,使用以下寫法
(function () {
        console.log('Welcome to the Internet. Please follow me.');
}());
  1. 拒絕在if,while等邏輯塊中直接聲明函數(shù)
// bad
if (currentUser) {
        function test() {
            console.log('fidding.');
        }
}
// good
let test;
if (currentUser) {
        test = () => {
            console.log('fidding.');
        };
}
  1. 函數(shù)定義風(fēng)格
// bad
const f = function(){};
const g = function (){};
const h = function() {};
// good
const x = function () {};
const y = function a() {};
  1. 時刻進行參數(shù)檢查驹暑,避免參數(shù)沖突
// bad
function f1(obj) {
        obj.key = 1;
};
// good
function f2(obj) {
        const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;
};
  1. 參數(shù)分配玫恳,檢測參數(shù)是否存在
// bad
function f1(a) {
        a = 1;
}
function f2(a) {
        if (!a) { a = 1; }
}
// good
function f3(a) {
        const b = a || 1;
}
function f4(a = 1) {
}

比較操作

  1. 盡量使用===!==代替==!=

  2. 避免冗贅

// bad
if (name !== '') {
}
// good
if (name) {
}
// bad
if (array.length > 0) {
}
// good
if (array.length) {
}
  1. 盡量避免三重嵌套(分開寫)并且嵌套不應(yīng)該分行
// bad
const foo = maybe1 > maybe2
        ? "bar"
        : value1 > value2 ? "baz" : null;
// better
const maybeNull = value1 > value2 ? 'baz' : null;
const foo = maybe1 > maybe2
        ? 'bar'
        : maybeNull;
// best
const maybeNull = value1 > value2 ? 'baz' : null;
const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
  1. 避免多余的三元運算符
// bad
const foo = a ? a : b;
const bar = c ? true : false;
const baz = c ? false : true;
// good
const foo = a || b;
const bar = !!c;
const baz = !c;

注釋

  1. 使用/** ... */多行注釋并包含描述以及指定所有參數(shù)和返回值的類型
// 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
 *
 * @param {String} tag
 * @return {Element} element
 */
function make(tag) {
        return element;
}
  1. 使用//單行注釋,注釋符//后添加一個空格并單獨一行优俘,如果注釋不是位于第一行的話需要在注釋前再空出一行
// 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;
}
  1. 使用// FIXME:注釋問題
class Calculator extends Abacus {
        constructor() {
            super();

    // FIXME: shouldn't use a global here
            total = 0;
        }
}
  1. 使用// TODO:注釋待做
class Calculator extends Abacus {
        constructor() {
            super();

        // TODO: total should be configurable by an options param
            this.total = 0;
        }
}

空格

  1. 使用4空格間隔(fidding個人喜好)
// bad
function foo() {
?const name;
}
// bad
function bar() {
??const name;
}
// good
function baz() {
????const name;
}
  1. ) , :前添加一個空格間隔
// bad
function test(){
        console.log('test');
}
// good
function test() {
        console.log('test');
}
// bad
dog.set('attr',{
        age: '1 year',
        breed: 'Bernese Mountain Dog'
});
// good
dog.set('attr', {
        age: '1 year',
        breed: 'Bernese Mountain Dog'
});
  1. if while等控制語句前以及大括號前添加一個空格間隔京办,函數(shù)聲明的參數(shù)列表和函數(shù)名稱之間沒有空格
// bad
if(isJedi) {
        fight ();
}
// good
if (isJedi) {
        fight();
}
// bad
function fight () {
        console.log ('Swooosh!');
}
// good
function fight() {
        console.log('Swooosh!');
}
  1. 在運算符前添加空格
// bad
const x=y+5;
// good
const x = y + 5;
  1. 塊和在下一個語句之前,留下一個空白行
// bad
const obj = {
        foo() {
        },
        bar() {
        }
};
// good
const obj = {
        foo() {
        },

        bar() {
        }
};
// bad
const arr = [
        function foo() {
        },
        function bar() {
        }
];
// good
const arr = [
        function foo() {
        },

        function bar() {
        }
];

逗號帆焕,

  1. 對象或數(shù)組結(jié)束行不附加,(個人習(xí)慣,兼容emacs js2-mode)
// bad
const hero = {
        firstName: 'Dana',
        lastName: 'Scully',
};
const heroes = [
        'Batman',
        'Superman',
];
// good
const hero = {
        firstName: 'Dana',
        lastName: 'Scully'
};
const heroes = [
        'Batman',
        'Superman'
];

jQuery

  1. 使用$來命名jQuery對象
// bad
const sidebar = $('.sidebar');
// good
const $sidebar = $('.sidebar');
// good
const $sidebarBtn = $('.sidebar-btn');

相關(guān)鏈接

  1. ECMAScript 6
  1. AirBnb JS編碼規(guī)范

原文地址:http://www.fidding.me/article/26

happy coding!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末惭婿,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子叶雹,更是在濱河造成了極大的恐慌财饥,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件折晦,死亡現(xiàn)場離奇詭異钥星,居然都是意外死亡,警方通過查閱死者的電腦和手機满着,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進店門谦炒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人风喇,你說我怎么就攤上這事编饺。” “怎么了响驴?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長撕蔼。 經(jīng)常有香客問我豁鲤,道長,這世上最難降的妖魔是什么鲸沮? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任琳骡,我火速辦了婚禮,結(jié)果婚禮上讼溺,老公的妹妹穿的比我還像新娘楣号。我一直安慰自己,他們只是感情好怒坯,可當(dāng)我...
    茶點故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布炫狱。 她就那樣靜靜地躺著,像睡著了一般剔猿。 火紅的嫁衣襯著肌膚如雪视译。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天归敬,我揣著相機與錄音酷含,去河邊找鬼鄙早。 笑死,一個胖子當(dāng)著我的面吹牛椅亚,可吹牛的內(nèi)容都是我干的限番。 我是一名探鬼主播,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼呀舔,長吁一口氣:“原來是場噩夢啊……” “哼弥虐!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起别威,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤躯舔,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后省古,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體粥庄,經(jīng)...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年豺妓,在試婚紗的時候發(fā)現(xiàn)自己被綠了惜互。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,841評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡琳拭,死狀恐怖训堆,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情白嘁,我是刑警寧澤坑鱼,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站絮缅,受9級特大地震影響鲁沥,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜耕魄,卻給世界環(huán)境...
    茶點故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一画恰、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧吸奴,春花似錦允扇、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至逞度,卻和暖如春额划,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背档泽。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工俊戳, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留揖赴,地道東北人。 一個月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓抑胎,卻偏偏與公主長得像燥滑,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子阿逃,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,781評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 第5章 引用類型(返回首頁) 本章內(nèi)容 使用對象 創(chuàng)建并操作數(shù)組 理解基本的JavaScript類型 使用基本類型...
    大學(xué)一百閱讀 3,233評論 0 4
  • ??引用類型的值(對象)是引用類型的一個實例恃锉。 ??在 ECMAscript 中搀菩,引用類型是一種數(shù)據(jù)結(jié)構(gòu),用于將數(shù)...
    霜天曉閱讀 1,054評論 0 1
  • 第2章 基本語法 2.1 概述 基本句法和變量 語句 JavaScript程序的執(zhí)行單位為行(line)破托,也就是一...
    悟名先生閱讀 4,149評論 0 13
  • 本章內(nèi)容 使用對象 創(chuàng)建并操作數(shù)組 理解基本的 JavaScript 類型 使用基本類型和基本包裝類型 引用類型的...
    悶油瓶小張閱讀 681評論 0 0
  • 今天簡單學(xué)習(xí)了一下markdown的語法肪跋,記錄如下: 0、標(biāo)題 如果想將一段文字定義為標(biāo)題土砂,只需要在這段文字前面加...
    Aobatu閱讀 265評論 0 0