ES6编程风格

154 阅读2分钟

1、let取代var,在let和const之间,优先使用const

2、静态字符串一律使用单引号或反引号,不使用双引号。动态字符串使用反引号

const a = 'hello';
const b = `world`;
const c = `${a} ${b}`;

3、解构赋值

// 使用数组成员对变量进行赋值时,优先使用解构赋值
const arr = [1, 2, 3];

// 不建议使用
const first = arr[0];
const second = arr[1];

// 建议使用
const [first, second] = arr;

// 函数的参数如果是对象的成员,优先使用解构赋值

// 不建议使用
function getFullName(user) {
    const firstName = user.firstName;
    const lastName = user.lastName;
}

// 建议使用
function getFullName(user) {
    const { firstName,  lastName } = user;
}
function getFullName({ firstName, lastName }) {}

// 如果函数返回多个值,优先使用对象的解构赋值,而不是数组的解构赋值

// 不建议使用
function f() {
    return [a, b, c];
}

// 建议使用
function f() {
    return { a, b, c }; // 方便以后添加返回值
}

4、对象

// 单行定义的对象最后一个成员不以逗号结尾,多行定义的对象最后一个以逗号结尾
const obj = { key1: value1, key2: value2 };
const obj = {
    key1: value1,
    key2: value2,
}

// 对象尽量静态化,最好不要随意添加属性,必须添加属性时,使用Object.assign()
const obj = {};
Object.assign(obj, { a: 1 });

5、数组

// 使用扩展运算符(...)拷贝数组
const arr = [1, 2];
const arrCopy = [...arr];

// 使用Array.from()将类似数组对象转为数组
const ele = document.querySelectorAll('div');
const nodes = Array.from(ele);

6、函数

// 立即执行函数可以写成箭头函数的形式
(() => {
    console.log('hello');
})();

// 匿名函数当做参数的场合,尽量使用箭头函数代替
[1, 2, 3].map(x => x * x);

简单的、单行的、不会复用的函数,建议采用箭头函数。如果函数体较为复杂,行数较多,还是应该采用传统的函数写法。

不要在函数体内使用 arguments 变量,使用 rest 运算符(...)代替。因为 rest 运算符显式表明你想要获取参数,而且 arguments 是一个类似数组的对象,而 rest 运算符可以提供一个真正的数组。

// 不建议使用
function f() {
    const args = Array.prototype.slice.call(arguments);
    return args.join('');
}

// 建议使用
function f(...args) {
    return args.join('');
}

// 使用默认值语法设置函数参数的默认值
function g(params = {}) {}

7、Class类

// 总是用class取代需要进行prototype的操作

// 不建议使用
function F(params = []) {
    this.arr = [...params];
}
F.prototype.pop = function () {
    const value = this.arr[0];
    this.arr.slice(0, 1);
    return value; 
}

// 建议使用
class F {
    constructor(params = []) {
        this.arr = [...params];
    }
    pop() {
        const value = this.arr[0];
        this.arr.slice(0, 1);
        return value;
    }
}

// 使用extends实现继承
class A extends B {
    constructor() {}
}