ES6对象的super关键字

ES6对象的super关键字

super是es6新出的关键字,它既可以当作函数使用,也可以当作对象使用,两种使用方法不尽相同

1.super用作函数使用的时候,代表父类的构造函数,es6规定在子类中使用this之前必须先执行一次super函数,super相当于Father.prototype.constructor.call(this)

class Father{
    constructor(){
        this.a = 1;
    }
}
class Son extends Father{
    constructor(){
        super();
    }
}

2.super用作对象的时候,在普通方法中指向父类的原型对象,在静态方法中指向父类

子类中使用super无法访问Father的实例属性a,可以访问原型对象上的p

class Father {
    constructor() {
        this.a = 1;
    }
    p() {
      console.log(thia.a);
        console.log('hello');
    }
}
class Son extends Father {
    constructor() {
        super();
     this.a = 2;
        super.p();//'2 hello'   Father.prototype.p()方法内部的this指向的是子类实例
        super.a;//undefined
    }
}

静态方法中指向的是父类,而非父类的构造函数
static method中super指向父类Parent,相当于访问Parent.myMethod
普通 method中super指向父类Parent的prototype,相当于访问Parent.prototype.myMethod

class Parent {
    static myMethod(msg) {
        console.log('static', msg);
    }
    myMethod(msg) {
        console.log('instance', msg);
    }
}
class Child extends Parent {
    static myMethod(msg) {
        super.myMethod(msg);  //super指向父类因此访问的是static myMethod
    }
    myMethod(msg) {
        super.myMethod(msg);  //super指向的是父类的构造函数,访问的是Parent.prototype.myMethod
    }
}
Child.myMethod(222);//static 222

let child = new Child;
child.myMethod(111);//instance 111

在这里插入图片描述

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值