Created
December 24, 2016 10:12
-
-
Save m3g4p0p/701f524997cacb7c89f0b4c12aa3a5aa to your computer and use it in GitHub Desktop.
A universal factory function
This file contains hidden or 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
const make = function make ({ | |
proto = {}, | |
self = {}, | |
init = function init (obj) { | |
Object.assign(this, obj) | |
return this | |
}, | |
mixins = [] | |
}) { | |
const mixProto = {} | |
const mixSelf = {} | |
mixins.forEach(mixin => { | |
const current = mixin() | |
Object.assign(mixProto, Object.getPrototypeOf(current)) | |
Object.assign(mixSelf, current) | |
}) | |
Object.assign(mixProto, proto) | |
Object.assign(mixSelf, self) | |
return function makeInstance (...args) { | |
const instance = Object.create(mixProto) | |
Object.assign(instance, mixSelf) | |
return init.apply(instance, args) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is basically a universal factory function for creating and mixing objects with a given prototype. The idea is heavily inspired by Eric Elliott's stampit, but it's much more minimalist in its API and implementation.
Sample usage:
MIT @ m3g4p0p