• ES5的继承与ES6的继承的区别——FEI面试官养成系列


    ES5的继承

    ES5的继承是先创建子类的实例, 然后再创建父类的方法添加到this上.

    通过原型和构造函数机制实现的.

    // ES5的继承
    // 原型链方式: 子类的原型指向父类的实例
    // 缺点: 1. 因为原型链继承共享实例属性,属于引用类型传值, 修改某个实例的属性会影响其他的实例 2. 不能实时向父类的构造函数中传值, 很不方便
    function Parent() {
        this.values = [1];
    }
    function Child(){
    
    }
    Child.prototype = new Parent();
    const child1 = new Child();
    console.log(child1.values); // [ 1 ]
    child1.values.push(2);
    const child2 = new Child();
    console.log(child2.values); // [ 1, 2 ]

    ES6的继承

    ES6的继承是先创建父类的实例对象this(必须先调用super方法), 再调用子类的构造函数修改this.

    通过关键字class定义类, extends关键字实现继承. 子类必须在constructor方法中调用super方法否则创建实例报错. 因为子类没有this对象, 而是使用父类的this, 然后对其进行加工

    super关键字指代父类的this, 在子类的构造函数中, 必须先调用super, 然后才能使用this

    // ES6的继承
    // 在子类的构造器中先调用super(), 创建出父类实例, 然后再去修改子类中的this去完善子类
    class Parent {
        constructor(a, b) {
            this.a = a;
            this.b = b;
        }
    }
    
    class Child extends Parent {
        constructor(a, b, c) {
            super(a, b);
            this.c = c;
        }
    }
    
    const child = new Child(1, 2, 3);
    console.log(child); // { a: 1, b: 2, c: 3 }
    用心写代码,不辜负程序员之名。
  • 相关阅读:
    python pyinotify模块详解
    lastpass密码管理工具使用教程
    MAMP 环境下安装Redis扩展
    SourceTree使用方法
    Mac securecrt 破解
    Memcache 安装
    Warning: setcookie() expects parameter 3 to be long, string given
    SQLSTATE[HY000] [2002] Connection refused
    插件管理无法访问
    光栅化渲染器
  • 原文地址:https://www.cnblogs.com/thinkingthigh/p/15594619.html
Copyright © 2020-2023  润新知