除了傳統的面向對象繼承方式,還流行一種經過可重用組件建立類的方式,就是聯合另外一個簡單類的代碼。app
// Disposable Mixin class Disposable { isDisposed: boolean; dispose() { this.isDisposed = true; } } // Activatable Mixin class Activatable { isActive: boolean; activate () { this.isActive = true; } deactivate () { this.isActive = false; } } // SmartObject這個類結合了這兩個mixins,不用extends,而是使用implements,。把類當成接口,僅使用兩個mixins類的類型而非實現。這意味着咱們須要在類裏面實現接口。可是這是咱們在用mixins時想避免的。因此咱們能夠爲將要mixins進來的屬性方法建立出佔位屬性。 class SmartObject implements Disposable, Activatable { constructor(){ setInterval(() => { console.log(`${this.isActive} : ${this.isDisposed}`); }, 500); } interact () { this.activate(); } isDisposed: boolean = false; dispose: () => void; isActive: boolean = false; activate: () => void; deactivate: () => void; } // 把mixins混入定義的類,完成所有實現部分 applyMixins(SmartObject, [Disposable, Activatable]); let smartObj = new SmartObject(); setTimeout(() => { smartObj.interact() }, 1000); // 建立幫助函數,幫咱們作混入操做。會遍歷mixins上的全部屬性,並複製到目標上去,把以前的佔位屬性替換成真正的實現代碼。 function applyMixins (deriveCtor: any, baseCtors: any[]) { baseCtors.forEach(baseCtor => { Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => { deriveCtor.prototype[name] = baseCtor.prototype[name]; }); }); }