美文网首页
fidding编码规范之JS篇

fidding编码规范之JS篇

作者: Fidding | 来源:发表于2018-04-18 18:04 被阅读0次

    良好的编程规范是打造优秀代码的基础,以下是fidding个人编码规范整理,使用ECMAScript 6.0(ES6)标准,并借鉴了许多文章与书籍的优秀编码习惯,本人也将持续更新与改进。

    变量与常量

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

    对象Object

    1. 使用{}直接创建对象
    // 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
    };
    

    数组Array

    1. 使用[]直接创建数组
    // bad
    const array = new Array();
    // good
    const array = [];
    
    1. 使用push添加数组项
    const array = [];
    // bad
    array[array.length] = 'abc';
    // good
    array.push('abc');
    
    1. 使用数组展开符...拷贝数组
    // 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. 尽可能使用模版代替字符串串联拼接
    // 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()来解析字符串,会造成很多安全问题。

    函数Function

    1. 当需要立即调用函数时,使用以下写法
    (function () {
            console.log('Welcome to the Internet. Please follow me.');
    }());
    
    1. 拒绝在if,while等逻辑块中直接声明函数
    // bad
    if (currentUser) {
            function test() {
                console.log('fidding.');
            }
    }
    // good
    let test;
    if (currentUser) {
            test = () => {
                console.log('fidding.');
            };
    }
    
    1. 函数定义风格
    // bad
    const f = function(){};
    const g = function (){};
    const h = function() {};
    // good
    const x = function () {};
    const y = function a() {};
    
    1. 时刻进行参数检查,避免参数冲突
    // bad
    function f1(obj) {
            obj.key = 1;
    };
    // good
    function f2(obj) {
            const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;
    };
    
    1. 参数分配,检测参数是否存在
    // 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. 尽量避免三重嵌套(分开写)并且嵌套不应该分行
    // 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. 使用/** ... */多行注释并包含描述以及指定所有参数和返回值的类型
    // 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等控制语句前以及大括号前添加一个空格间隔,函数声明的参数列表和函数名称之间没有空格
    // 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. 对象或数组结束行不附加,(个人习惯,兼容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');
    

    相关链接

    1. ECMAScript 6
    1. AirBnb JS编码规范

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

    happy coding!

    相关文章

      网友评论

          本文标题:fidding编码规范之JS篇

          本文链接:https://www.haomeiwen.com/subject/qglbkftx.html