Created
March 11, 2019 16:40
-
-
Save nhamilakis/b8fb95a90dc04211f65a4b8885af1e22 to your computer and use it in GitHub Desktop.
Mixins idea in Typescript/Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Exposable { | |
public exposeFunctions: () => Array<string>; | |
} | |
// TODO: fix function prototype.add | |
function applyMixins(derivedCtor: any, baseCtors: Array<Exposable>) { | |
baseCtors.forEach((baseCtor) => { | |
baseCtor.prototype.exposeFunctions().forEach(funct => { | |
Object.setPrototypeOf(derivedCtor, { | |
funct: baseCtor.prototype[funct] | |
}) | |
}) | |
}); | |
} | |
class Disposable implements Exposable { | |
disposable: boolean = false; | |
public isDisposable(): boolean { | |
return this.disposable; | |
} | |
public exposeFunctions() : Array<string> { | |
return ['isDisposable']; | |
} | |
}; | |
class Activatable { | |
active: boolean = false; | |
public activate(): void { | |
this.active = true; | |
} | |
public deactivate(): void { | |
this.active = false; | |
} | |
public isActive(): boolean { | |
return this.active; | |
} | |
public exposeFunctions() : Array<string> { | |
return ['activate', 'deactivate', 'isActive']; | |
} | |
}; | |
class SuperCombo { | |
active: boolean = false; | |
disposable: boolean = false; | |
constructor(){ | |
applyMixins(this, [Disposable, Activatable]) | |
} | |
} | |
// main | |
let comboMeal = new SuperCombo(); | |
console.log(comboMeal); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment