Reputation: 48
anyone knows how to get all properties from an inherited class and put the current properties in just one Object with ES6?
export class MainClass {
constructor(classInstance) {}
myMethodMain {
//doSomhethig
}
}
file 2
class Another extends MainClass {
constructor(config) {
this.name = 'testing';
}
myMethodAnother {
//doSomhethig
}
}
file 3
class RandomClass {
constructor() {
this.name = 'test';
}
myMethodRamdonChild {
//doSomhethig
}
}
file 3
class RandomChild extends RandomClass {
myMethodRamdonChild {
//doSomhethig
}
}
export const myMainClass = new Another(new RandomChild());
I need in the constructor of my MainClass copy all properties from RandomChild and the super class RandomClass and maintain the current properties from my current class too. In the final i need an Object with all properties like that.
newObject{
myMethodMain {
//doSomhethig
}
myMethodAnother {
//doSomhethig
}
myMethodRamdonChild {
//doSomhethig
}
myMethodRamdonChild {
//doSomhethig
}
}
I have tried to use(_.merge, _.copy, angular.copy, angular.merge, $.merge, Object.assign, Object.merge
) and other methods.
Important: I can't change my current structure
Upvotes: 2
Views: 248
Reputation: 48
i solved my problem with this.
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
has all properties from my classes :)
Upvotes: 1