2016-10-13 15 views
1

継承されたクラスからすべてのプロパティを取得し、現在のプロパティをES6で1つのオブジェクトに入れる方法を知っている人は誰ですか?継承されたクラスを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()); 

メインクラスのコンストラクタで、RandomChildのすべてのプロパティとスーパークラスRandomClassをコピーし、現在のクラスの現在のプロパティも保持する必要があります。 最終的に私はそのようなすべてのプロパティを持つオブジェクトが必要です。

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

Iは、(_.merge, _.copy, angular.copy, angular.merge, $.merge, Object.assign, Object.merge)を使用しようとする他の方法しています。

重要:私はこれで私の問題を解決し

+0

が正しい答えを受け入れる代わりにsolved' 'にタイトルを変更してください私のクラス:)からすべてのプロパティを持っています。自己受け入れが許可されています – DarkBee

答えて

1

私の現在の構造を変更することはできません。

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

+1

'obj.constructor.prototype'の代わりに、本当に' Object.getPrototypeOf(Object(obj)) ' – Bergi

関連する問題