个人学习笔记 - ES6部分语法规范

107 阅读2分钟

类与构造函数

使用class语法,避免直接操作prototype;同理继承使用extends

//bad
//构造函数
function fQueue(name = 'admin') {
    this.name = name;
    this.pop = function () {}  //实例化方法,构造函数不可用
}
fQueue.pop = function () {}; //构造函数内置方法,实例不可用
fQueue.prototype.pop = function () {}  //原型链方法,均可用,但是对原型链造成了污染

//good
class Queue {
    constructor(name = 'admin') {
        this.name = name;
        this.pop = function () {}  //实例化方法,构造函数不可用
    };
    pop() {} 
}
class Peekable extends Queue {
    peek() {}
}

this可以实现链式调用

class Jedi {
    fJump() {
        this.jumping = true;
        return this
    };
    fSetHeight(height = 10) {
        this.height = height;
        return this
    }
};
const luke = new Jedi();
luke.fJump()
    .fSetHeight(100);

// {jumping: true, height : 100}

类存在默认的构造方法;空的构造函数或是继承父类的构造函数不需要写

一个实例方法应该根据实例的属性有不同行为,即为非静态方法--否则类方法应该使用this或被写成静态方法

class Jedi {
    fGetBar() {
        console.log(this.bar)
    };
    static fGetBar() {
        console.log('bar')
    }
}

迭代器与生成器

用迭代方法替换for-infor-of

const numbers = [1, 2, 3, 4, 5];
//best
const sum = numbers.reduce((total, num) => total + num, 0);
//godd
let sum = 0;
numbers.forEach((num) => sum += num)

使用class语法,避免直接操作prototype;同理继承使用extends

//bad
//构造函数
function fQueue(name = 'admin') {
    this.name = name;
    this.pop = function () {}  //实例化方法,构造函数不可用
}
fQueue.pop = function () {}; //构造函数内置方法,实例不可用
fQueue.prototype.pop = function () {}  //原型链方法,均可用,但是对原型链造成了污染

//good
class Queue {
    constructor(name = 'admin') {
        this.name = name;
        this.pop = function () {}  //实例化方法,构造函数不可用
    };
    pop() {} 
}
class Peekable extends Queue {
    peek() {}
}

this可以实现链式调用

class Jedi {
    fJump() {
        this.jumping = true;
        return this
    };
    fSetHeight(height = 10) {
        this.height = height;
        return this
    }
};
const luke = new Jedi();
luke.fJump()
    .fSetHeight(100);

// {jumping: true, height : 100}

类存在默认的构造方法;空的构造函数或是继承父类的构造函数不需要写

一个实例方法应该根据实例的属性有不同行为,即为非静态方法--否则类方法应该使用this或被写成静态方法

class Jedi {
    fGetBar() {
        console.log(this.bar)
    };
    static fGetBar() {
        console.log('bar')
    }
}

属性

访问属性用点符号,用变量获取用方括号

const oLuck = {
    jedi: true,
    age: 28
};
const bJedi = oLuck.jedi

变量

将变量声明放在合理的位置

function fCheckName(hasName) {
    if (hasName ==== 'test') {
        return false
    }
    
    const name = getName();
    if (name === 'test') {
        this.setName('');
        return false
    }
    return name
}

不要使用链式声明变量;会创建隐式全局变量

function fExample() {
    //bad
    let a = b = 1;

    //good
    let a = 1;
    let b = a;
}