• 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  
  • 相关阅读:
    番剧下载器
    ☕️【系统设计】如何设计出优雅且实用的 API 接口
    对象在内存中的内存布局是什么样的?
    稍等,我手机帮你远程调试下代码!
    Redis持久化整理
    git fork模式整理
    Java Lambda 表达式源码分析
    Java Stream 源码分析
    JVM G1GC的算法与实现
    域控批量创建域用户,并授权组
  • 原文地址:https://www.cnblogs.com/yinping/p/11234019.html
Copyright © 2020-2023  润新知