Skip to content

Instantly share code, notes, and snippets.

@nhamilakis
Created March 11, 2019 16:40
Show Gist options
  • Save nhamilakis/b8fb95a90dc04211f65a4b8885af1e22 to your computer and use it in GitHub Desktop.
Save nhamilakis/b8fb95a90dc04211f65a4b8885af1e22 to your computer and use it in GitHub Desktop.
Mixins idea in Typescript/Javascript
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