Skip to content

Instantly share code, notes, and snippets.

@gmmorris
Last active November 1, 2015 16:46
Show Gist options
  • Save gmmorris/df5aecc4d53981793c62 to your computer and use it in GitHub Desktop.
Save gmmorris/df5aecc4d53981793c62 to your computer and use it in GitHub Desktop.
An example of a Constructor Composer for my How to Grok a Higher Order Class article
export default function(methodComposer) {
return ClassToCompose => {
const proto = ClassToCompose.prototype;
return class extends ClassToCompose {
constructor() {
super(...arguments);
for (const prop of Object.getOwnPropertyNames(proto)) {
const method = proto[prop];
const {configurable, writable} = Object.getOwnPropertyDescriptor(proto, prop);
if (method instanceof Function &&
// we can't change non configurable or writable methods
configurable && writable &&
// touching the constructor won't help us here, as we're modifying an existing instance
method !== ClassToCompose) {
this[prop] = methodComposer(proto[prop], prop);
}
}
}
};
};
}
import constructorComposer from './extend_constructor_composer';
/**
* We'll use the same ComposableBaseClass class and verbosify function from before
*/
/**
* Constructor Composite Example
*/
// create verbosified factory creator - this would only be done once per function, so it would only be used once for the 'verbosify' function in your codebase
const createVerbosifiedConstructorClass = constructorComposer(verbosify);
// create verbosified factory of the composable class - this would be used per class you wish to attach the verbose beahviour to
const VerbosifiedConstructorComposedClass = createVerbosifiedConstructorClass(ComposableBaseClass);
// usage of factory every time you want a verbose instance of ComposableBaseClass
myVerboseInstance = new VerbosifiedConstructorComposedClass();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment