ES6

作者: 没了提心吊胆的稗子 | 来源:发表于2019-08-13 14:33 被阅读0次

var
可以重复声明
不能定义常量
不支持块级作用域
let const
不会变量提升
不能重复声明
支持块级作用域
(效果跟闭包一样)
const声明的常量不允许重新赋值

解构
分解一个对象的结构
解构的时候等号两边结构类似,右边必须是一个真实的值


默认参数


箭头函数


let obj1 = {
    name: 'js',
    getName: ()=> {
        //   箭头函数中的this是定死的 指向外层的this 谁调都不管用
        console.log(this.name);
    }
};

let obj2 = {
    name: 'html',
    gN: obj1.getName
};

obj2.gN(); // undefined

Object.setPrototype(obj, obj1)
设置obj的原型是obj1
obj._proto_ = obj1
Object.getPrototype(obj)
获取obj的原型

class
es5中的类里可以定义构造函数,创建一个类实例的时候就会调用构造函数,构造函数中的属性是实例的私有属性,其余属于原型上的属性,也就是共有属性。静态属性是属于类的,不需要实例就可以调用


类的继承
首先判断父类是不是一个类,不是的话就报错,
是的话,重写子类构造函数的原型,
subClass.prototype = Object.create(superClass && superClass.prototype, {})
// Object.create方法实现
Object.create = function(prototype){
  function Fn(){};
  Fn.prototype = prototype;
  return new Fn();
}

静态属性是属于类的(会添加在Constructor上),不需要通过实例来调用,一个属性如果放在原型上的话,是要通过实例来调用的,放在类上就只能通过类名来调用。

class Parent{
    static sayName() {
        console.log(1);
    }
}
class Child extends Parent{
}
Parent.sayName();
Child.sayName();
var child = new Child();
child.sayName();

es5中父类的私有属性不能被继承

function Parent(name, age) {
    this.name = name;
    this.age = age;
}
Parent.prototype.getName = function () {
    return this.name;
};

// 父类上自定义属性
Parent.num = 1;
Parent.sagNum = function (num) {
    return num;
};

function Child(name, age, sex) {
    Parent.call(this, name, age);
    this.sex = sex;
}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

var child = new Child('lulu', 23, 'female');

console.log(child.num);  // undefined
console.log(Child.num);   // undefined
child.sagNum(2);  // TypeError: child.sagNum is not a function

生成器(Generator)和迭代器(Iterator)
理解koa的基础,也是async await的基础

// es5模拟
// 生成器 生成迭代器
function read(books) {
    let index = 0;
    return {
        next() {
            let done = index === books.length;
            let value = books[index++];
            return {
                value,
                done
            }
        }
    }
}
// 迭代器 不停调用next方法得到一个结果{value, done}
// done为true的时候就表示取完了
let it = read(['js', 'node']);
var cur = {};
while(! cur.done){
    cur = it.next();
    console.log(cur);
}

// es6
function *read(books) {
    console.log('开始');
    for (let i = 0; i < books.length; i++) {
        // 相当于断点,在这里产出一个结果
        // let b = yield 'a'  yield前是下次的输入 后是本次的输出
        yield books[i]
    }
    console.log('结束');
}
let it = read(['js', 'node']);
let cur = {};
while(! cur.done){
    // 第一次next传参是没有意义的,调用方法的时候传的参数会直接给第一次next
    cur = it.next();
    console.log(cur);
}

相关文章

网友评论

      本文标题:ES6

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