JavaScript Mixins
Let’s start by defining what a mixin is. I would explain it as a way to share set of data (functions, methods, variables…) with objects.
How does that look like? Let’s say we have two functions Clark
and Bruce
and that we want to implement two methods sayName
and secretIdentity
to their prototypes.
This is how our functions would look like:
Most common ways of adding the methods these functions are:
1. Extending objects
Extending object doesn’t really fit our description of mixins, since we are extending instead mixing, though idea is the same. At least that’s the way I see it.
Biggest downside to this approach is that you’ll either need extend
function available from some library like Underscore or jQuery or you would have to write it.
2. Functional mixin
They don’t require any additional library and they are faster compared to extending. Also I find this implementation frequently overlooked.
Which approach do you prefer?