zoukankan      html  css  js  c++  java
  • 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  
  • 相关阅读:
    记第一次为开源代码报漏洞
    入职第三周——总结前两周学习内容
    入职一星期之感想
    毕业季之礼
    基于mint-ui的移动应用开发案例二(项目搭建)
    基于mint-ui的移动应用开发案例一(简介)
    工作笔记一——杂项
    微信小程序实战小小应用——豆瓣电影
    React学习之坑(二)- 基础入门
    React学习笔记(一)- 环境搭建
  • 原文地址:https://www.cnblogs.com/yinping/p/11234019.html
Copyright © 2011-2022 走看看