[英]Copy an inherited class to another in ES6
有谁知道如何从继承的类中获取所有属性并将当前属性放在一个带有 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
拥有我的课程中的所有属性:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.