zoukankan      html  css  js  c++  java
  • object.assign拷贝prototype实现多继承

    1. 单继承

    // Shape - 父类(superclass)
    function Shape() {
      this.x = 0;
      this.y = 0;
    }
    
    // Rectangle - 子类(subclass)
    function Rectangle() {
      //借用父类构造函数
      Shape.call(this);
    }
    
    // 子类续承父类
    Rectangle.prototype = Object.create(Shape.prototype);
    // 恢复构造函数
    Rectangle.prototype.constructor = Rectangle;

    2. 多继承

    function MyClass() {
        //所有父类构造函数借用
        SuperClass.call(this);
        OtherSuperClass.call(this);
    }
    
    // 使用Object.create继承一个类,此时继承了SuperClass的原型链
    MyClass.prototype = Object.create(SuperClass.prototype);
    
    // 使用Object.assign拷贝其他父类的方法到自身的prototype
    Object.assign(MyClass.prototype, OtherSuperClass.prototype);
    
    // 恢复constructor
    MyClass.prototype.constructor = MyClass;
    
    //若不使用Object.create, 全部使用Object.assign, 对象为使用{},会继承Object的原型链,造成原型链断裂
    //MyClass.prototype = Object.assign({},SuperClass.prototype,OtherSuperClass.prototype);
  • 相关阅读:
    2019.03.20 mvt,Django分页
    2019.03.18 连接my sql
    第三方包
    飞机大战完结篇
    Python复习基础篇
    final、权限、内部类
    接口、多态
    继承、super、this、抽象类
    String类、static、Arrays类、Math类
    Scanner类、Random类、ArrayList类
  • 原文地址:https://www.cnblogs.com/mengff/p/12854089.html
Copyright © 2011-2022 走看看