ES6对象的super关键字

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

一、super作为函数

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

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

二、super作为对象

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
复制代码

 

参考来源:https://www.cnblogs.com/yinping/p/11234019.html

 

posted @   盼星星盼太阳  阅读(350)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示