ES6继承

1.继承方式

ES6中使用extends关键字实现继承

class subType extends superType{
    ...
}

与es5的继承,子类创建自己的this,然后父类对其加工不同,es6的继承原理是,继承父类的this,并在此基础上进行修改。因此,实现继承必须要在constructor中调用父类的构造函数,super:

class subType extends superType{
    constructor(){
        super();
        ...
    }
}

如果子类没有定义constructor函数,那么将默认添加这个方法。

 

2.super关键字

1.super当作函数

super当作函数只能放在constructor()函数中进行使用,表示父类的构造函数。

2.super当作对象

super当作对象又可分为表示子类的this,和表示父类

2.1super表示子类的this

当对super进行赋值操作时,super被当成是子类的this。对super的某属性进行赋值就相当于对子类的this中的该属性进行赋值操作。

class subType extends superType{
    constructor(){
        super();
        this.name="sub";
        super.name="haha"
        console.log(this.name);   //"haha"
    }
}

2.2super表示父类对象

当对super进行取值操作时,super表示父类对象

class superType{
    showName(){
        console.log(this.name);
    }
}

class subType extends superType{
    constructor(){
        super();
        this.name="sub";
        super.showName();   //"sub"
    }
}

这里表示在子类上下文中调用父类的showName方法,因此showName的this是子类的this

 

prototype属性

子类的__proto__属性指向父类,表示构造函数的继承。

子类的prototype的__proto__指向父类的prototype:表示原型的继承。

三种特殊情况:

1.子类继承Object

class A extends Object{
}
A.__proto__===Object//true
A.prototype.__proto__===Object.prototype//true

2.子类没有任何继承

class A{
}
A.__proto__===Function.prototype//true
A.prototype.__proto__===Object.prototype//true

3.子类继承null

class A extends Null{
}
A.__proto__===Object//true
A.prototype.__proto__===undefined//true

 

原生构造函数的继承

ES6可以对原生的构造函数进行继承和修改。ES5不能构造函数的修改,是因为ES5的继承方式是创建自己的this,然后调用父类构造函数进行修改,原生构造函数会忽略通过apply改变this的操作。而ES6直接继承父类的this。

 

posted @ 2020-06-30 15:51  程嘿嘿  阅读(448)  评论(0编辑  收藏  举报