在ES6中将一个继承的类复制到另一个

Copy an inherited class to another in ES6

本文关键字:继承 复制 另一个 一个 ES6      更新时间:2023-09-26

有人知道如何从继承类中获得所有属性,并将当前属性放在ES6的一个对象中吗?

export class MainClass  {
   constructor(classInstance) {} 
   myMethodMain {
     //doSomhethig
   }  
}

文件2

class Another extends MainClass {
  constructor(config) {
      this.name = 'testing';
  }
  myMethodAnother {
  //doSomhethig
  }
}
文件

3

class RandomClass {
    constructor() {
      this.name = 'test';
    }
    myMethodRamdonChild { 
    //doSomhethig
    }
}
文件

3

class RandomChild extends RandomClass {
    myMethodRamdonChild {
    //doSomhethig
   }
}
export const myMainClass = new Another(new RandomChild());

我需要在我的MainClass的构造函数复制所有的属性从RandomChild和超类RandomClass和维护当前的属性从我当前的类太。最后,我需要一个具有所有属性的对象。

newObject{
  myMethodMain {
  //doSomhethig
  }
  myMethodAnother {
  //doSomhethig
  }
  myMethodRamdonChild { 
    //doSomhethig
  }
  myMethodRamdonChild {
    //doSomhethig
  }
}

我已经尝试使用(_.merge, _.copy, angular.copy, angular.merge, $.merge, Object.assign, Object.merge)和其他方法。

重要:我不能改变当前的结构

我解决了我的问题。

export const bind = (target) => (obj) => isFunction(target) ? target.bind(obj) : target;
export const pack = (keys) => (obj) => keys.reduce((res, key) => Object.assign(res, {[key]: bind(obj[key])(obj)}), {});
export const getAllProperties = (o) => {
    let results = [];
    function properties(obj) {
        let props, i;
        if (obj == null) {
            return results;
        }
        if (typeof obj !== 'object' && typeof obj !== 'function') {
            return properties(obj.constructor.prototype);
        }
        props = Object.getOwnPropertyNames(obj);
        i = props.length;
        while (i--) {
            if (!~results.indexOf(props[i])) {
                results.push(props[i]);
            }
        }
        return properties(Object.getPrototypeOf(obj));
    }
    return properties(o);
};
Object.assign(self, pack(getAllProperties(jmi))(jmi));

self从我的类的所有属性:)