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);
  • 相关阅读:
    特殊方法(双下方法)
    反射
    属性
    类方法、静态方法
    封装
    python接口类,抽象类
    Yii2基本概念之——事件(Event)
    Yii2基本概念之——行为(Behavior)
    yii2 migrate 数据库迁移的简单分享
    Yii2.0 RESTful API 之速率限制
  • 原文地址:https://www.cnblogs.com/mengff/p/12854089.html
Copyright © 2011-2022 走看看