Last active
November 1, 2015 16:46
-
-
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
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
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); | |
} | |
} | |
} | |
}; | |
}; | |
} |
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
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