ES6 -类的继承-super 学习笔记

类的继承中必须提到的关键字:super。派生类的方法通过super来引用它们的原型。

使用场景:

仅允许在派生类类构造函数、实例方法、静态方法中使用

class Venhicel {
    constructor (){
        console.log('*************调了父类的构造函数',this); //1. Bus {}
        this.hasEngine = true;
    }
    static a=1;
    static b=2;
    static identify () {
        console.log('*************调了父类的static函数',this.b); // 
    }
}
// ES6的类继承策略:先实例后继承
class Bus extends Venhicel{
    constructor () {
        console.log('*************super', super()); //2.Bus { hasEngine: true }
        console.log(this instanceof Venhicel); // 3.true
        console.log('*************子类的this',this); //4.Bus { hasEngine: true }
    }
    static identify () {
        console.log('*************调了子类的static函数',this.a); // [class Bus extends Venhicel]
        super.identify();
    }

}
new Bus();
Bus.identify();

运行结果:

*************调了父类的构造函数 Bus {}

*************super Bus { hasEngine: true }

true

*************子类的this Bus { hasEngine: true }

*************调了子类的static函数 1

*************调了父类的static函数 2

super使用的注意点:

  • super只能在派生类的构造函数和静态方法中使用;
  • 不能单独引用super关键字,要门用它调用构造函数,要么用它引用静态方法;
  • 调用super()对调用父类的构造函数,并将返回的实例赋值给this;
  • super()的行为如同调用构造函数,若需要给父类构造函数传参,则需要手动传入;
  • 若没有没有定义派生类的构造函数,那么在实例化派生类时,会自动调用super(),并且,会传入所有传给派生类的参数;
  • 在派生类的构造函数中,不能在调用super()之前引用this;
  • 若派生类中显式定义了构造函数,则要门必须在其中调用super(),要么在其中返回一个对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值