Mixins
In JavaScript, we can look at inheriting from Mixins as a means of collecting functionality through extension. Each new object we define has a prototype from which it can inherit further properties. Prototypes can inherit from other object prototypes but, even more importantly, can define properties for any number of object instances. We can leverage this fact to promote function reuse (Figure 9-10).

Figure 9-10. Mixins
Mixins allow objects to borrow (or inherit) functionality from them with a minimal amount of complexity. As the pattern works well with JavaScript’s object prototypes, it gives us a fairly flexible way to share functionality from not just one Mixin, but effectively many through multiple inheritance.
They can be viewed as objects with attributes and methods that can be easily shared across a number of other object prototypes. Imagine that we define a Mixin containing utility functions in a standard object literal as follows:
varmyMixins={moveUp:function(){console.log("move up");},moveDown:function(){console.log("move down");},stop:function(){console.log("stop! in the name of love!");}};
We can then easily extend the prototype of existing constructor
functions to include this behavior using a helper such as the
Underscore.js _.extend() method:
// A skeleton carAnimator constructorfunctioncarAnimator(){this.moveLeft=function(){console.log ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access