zoukankan      html  css  js  c++  java
  • es6继承

    class Parent {
        constructor(x,y){
            this.x = x;
            this.y = y;
        }
        toString(){
    
        }
    }
    
    class Child extends Parent{
        constructor(x,y,color){
            super(x,y);
            this.color = color;
        }
        toString(){
            return super.toString();
        }
    }
    /*
    * 通过extends关键字继承了Parent类所有的属性和方法。
    * 子类的constructor方法 和 toString方法中都出现了super关键字,
    * 在这里表示父类的构造函数,用来新建父类的this对象。
    * 子类必须在constructor方法中调用super方法,因为子类的this对象必须通过父类的构造函数完成创建,
    * 并且得到与父类同样的实例属性和方法。如果不调用,子类就得不到this对象,就不能进行二次加工。
    * 要注意的一个地方是,在子类的构造函数中,只有调用super才可以使用this关键字,
    * 所以this关键字要放到super关键字之后,
    * 是因为子类实例的构建,基于父类实例,只有super方法能调用父类实例。
    */
    /*
    * ES5的继承实质是先创建子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this))
    * ES6的继承实质是先将父类实例对象的属性和方法加到this上面(所以需先调用super方法),然后再用子类构造函数修改this
    */
    
    class Child extends Parent{
    
    }
    //等同于
    class Child extends Parent{
        constructor(...args){
            super(...args);
        }
    }
    /*
    * 如果子类没有定义constructor方法,这个方法会被默认添加,
    * 也就是说不管有没有显示的定义,子类都有constructor方法。
    */
    class Parent {
    
    }
    
    class Child extends Parent{
        constructor(){
            super();
        }
    }
    
    /*
    * super这个关键字既可以当做函数使用,也可以当做对象使用
    * 作为函数调用时,代表父类的构造函数,子类构造函数必须执行一次super函数
    * super虽然代表了父类Parent的构造函数,但是返回的是子类Child的实例
    * 即super内部的this指的是Child,super在这里就相当于:
    * Parent.prototype.constructor.call(this)
    * super作为函数使用时,super()只能用在子类的构造函数中*/
    
    class Parent {
        outPut(){
            console.log(1)
        }
    }
    
    class Child extends Parent{
        constructor(){
            super();
            console.log(super.outPut())
        }
    }
    
    /*
    * super作为对象时,在普通方法中指向父类的原型对象,静态方法中指向父类
    * super在普通方法中代表Parent.prototype,所以super.outPut()就相当于
    * Parent.prototype.outPut()
    * 注意,父类实例上的方法或属性是无法通过super调用的*/
  • 相关阅读:
    Java中怎么控制线程訪问资源的数量
    我的Hook学习笔记
    《编写可读代码的艺术》——简单总结
    Hdu 1016 Prime Ring Problem (素数环经典dfs)
    setsockopt()使用方法(參数具体说明)
    Html5培训之精髓
    [unity3d]unity平台的预处理
    音频编辑大师 3.3 注冊名 注冊码
    linux tar.gz zip 解压缩 压缩命令
    面向对象的三个基本特征
  • 原文地址:https://www.cnblogs.com/sexintercourse/p/12269464.html
Copyright © 2011-2022 走看看