如何写出逻辑清晰简洁,好维护的Javascript代码?

一、代码简洁、逻辑清晰


使用ES6新特性

  • 字符串连接使用模板字符串 ` 和 ${} 代替 传统+

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    let name = 'jasonlam'
    let time = '8:00'

    // bad code
    let message = 'hello ' + name + ', it\'s ' + time +' now'
    console.log(message) // hello jasonlam, it's 8:00 now

    // good code
    let message = `hello ${name}, it's ${time} now`
    console.log(message) // hello jasonlam, it's 8:00 now
  • 使用解构赋值

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    // 一、简洁明了地获取对象、数组、函数return中的值

    const data = { name: 'jasonlam', age: 22 };

    // bad code
    let name = data.name; // jasonlam
    let age = data.age; // 22

    // good code
    const { name, age } = data; // 简单明了
    console.log(name) // jasonlam
    console.log(age) // 22

    --------------------------------------------

    const fullName = ['jason', 'lam'];

    // bad code
    let firstName = fullName[0];
    let lastName = fullName[1];

    // good code
    const [firstName, lastName] = fullName;
    console.log(firstName) // jason
    console.log(lastName) // lam

    // 二、交换变量的值

    let x = 1;
    let y = 2;
    [x, y] = [y, x];

    // 三、遍历Map结构

    const map = new Map();
    map.set('first', 'hello');
    map.set('second', 'world');

    for (let [key, value] of map) {
    console.log(key + " is " + value);
    }
    // first is hello
    // second is world

    // 四、加载模块的指定方法
    // 加载模块时,往往需要指定输入哪些方法。解构赋值使得输入语句非常清晰

    const { SourceMapConsumer, SourceNode } = require("source-map")
  • ES6 允许为函数的参数设置默认值,即直接写在参数定义的后面

  • 尾调用优化 - 尾递归,递归函数改写 - 函数curry化、参数默认值

二、可维护性


变量相关

  • 数据只使用一次或不使用就无需装到变量中(没用的就删除掉,不然过久了自己都不敢删,怕是不是哪里会用到)
  • 变量命名最好字面上就要看得懂并且尽可能简洁不啰嗦,别搞那些花里胡哨的
  • 特定的数值(参数)最好放在变量里并且要命名好,在JS与CSS预处理器(如Less or Sass)都有用武之地
1
2
3
4
5
6
7
8
9
10
11
12
// JS Bad Code:

if(value.length < 8){
// 为什么要小于8,8表示的是什么?长度,还是位移,还是高度?Oh,my God!!
}

// JS Good Code

const MAX_INPUT_LENGTH = 8;
if (value.length < MAX_INPUT_LENGTH) {
// 一目了然,判断中表示的是不能超过最大输入长度
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 这部分的代码并不具有很强的代表性,但就是希望告诉你可以这么做

// Less Bad Code
.text-line {
line-height: 20px;
}
.banner {
line-height: 60px;
}

// Less Good Code
@Banner_LINE_HEIGHT: 20px;
.text-line {
line-height: @Banner_LINE_HEIGHT; // 1行的高度
}
.banner {
line-height: @Banner_LINE_HEIGHT * 3; // 3行的高度
}

函数相关

  • 从函数名就可以知道返回值的类型,对于返回true or false的函数,最好以should/is/can/has开头
  • 功能函数最好为纯函数,一个函数完成一个独立的功能,不要一个函数混杂多个功能
  • 动作函数要以动词开头,如send/add/delete
  • 优先使用函数式编程

参考文章:
《看看这些被同事喷的JS代码风格你写过多少》 https://github.com/jackiewillen/blog/issues/14
《ECMAScript 6 入门》—— 阮一峰 http://es6.ruanyifeng.com/