2016-07-12 36 views
1

我想創建一個ES6類繼承2類(從外部庫),但ES6不允許這樣做。我也不能使用mixins。加工似乎是我唯一的選擇。漂亮的javascript模式的對象imbrication(模擬多重繼承)

對於這個例子,假設我想有一個UI組件類,它直接發出事件,記錄東西等(爲了多態的目的)。

我想避免以下模式:

class UIComponent extends React.Component { 
    constructor(props) { 
     super(props); 
     this.ee = new EventEmitter(); 
    } 

    /* 
    * methods of my UIComponent 
    */ 
    emitThis(val) { 
     this.emit('thisEvent', val); 
    }, 

    onThat(func) { 
     this.on('thatEvent', func); 
    }, 

    doThis() { 
     this.specificLog("i'm doing this"); 
     // do stuff 
    } 

    /* 
    * Here i just implement all methods of EventEmitter... 
    */ 
    on(...args) { 
     this.ee.on(...args); 
    } 

    once(...args) { 
     this.ee.once(...args); 
    } 

    emit(...args) { 
     this.ee.emit(...args); 
    } 

    /* this goes on and on... */ 
} 

不使用Javascript(ES5,ES6,ES2015)允許用於此目的的一些更好的模式?

+1

製作陣營組件發出似乎對正常的陣營架構戰鬥,但是忽略了,你絕對可以在事件發射器的實現作爲混合只要你使用了一個與之相關的書。 – loganfsmyth

+0

它違背了正常的React架構。我想避免這種模式(我需要重寫所有eventEmitter方法 - 實際上我需要使用更復雜的類,它本身繼承自eventEmitter ...) – Sebastien

+0

請參閱[JavaScript中的多重繼承/原型]( http://stackoverflow.com/q/9163341/1529630)。你可以使用proxys。 – Oriol

回答

1

在ES6的模式基本上是一個組合,在深副本父原型樣機的孩子,這樣的事情

class FosterParent { ...} 

class Child extends Parent { ...} 

let proto = FosterParent.prototype; 

do { 
    for (const key of Object.keys(proto)) 
    if (!(key in Child.prototype)) 
     Child.prototype[key] = proto[key]; 
} while (proto = Object.getPrototypeOf(proto)) 

上面的代碼過於簡單,因爲它的副本枚舉密鑰,而不是描述符。

在ES.Next或TypeScript裝飾器來救援。 @mixin decorator from core-decorators package應該做同樣的事情的描述,然而有許多靈巧的語法:

class FosterParent { ...} 

@mixin(FosterParent) 
class Child extends Parent { ...}