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

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

變量與常量

  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. 時刻進(jìn)行參數(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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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

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