What is a Mixin?
Original concept of mixin came from an ice cream shop that provided on-demand customizable ice cream. At these shops, customers can make their own flavor by mixing up different toppings. You would pick up an ice cream flavor and a bunch of toppings, and then you can choose to mix them inside the ice cream by smashing these together instead of sprinkling as a topping. Hence, these are called mixins.
In terms of programming, Mixins are these pieces of code that you can mix with other objects to extend their functionality. Basically, you can borrow features from different mixins to compose the kind of object you desire.
Inheritance vs Composition
Object.assign() method where you can borrow methods from two different mixins.
Composing Object using Mixins
In the following example, we have two objects jsSkill and degree, they both would serve as mixins when I combine their properties and copy into an empty object using the
Factory Function with closures
Having an inner variable inside the factory function will maintain the state inside a closure. The state will be stored inside every function that is using the variable.
Using a factory function with closures you can build function mixins. Each mixin would take an Object as a parameter and returns a new object that would take passed object and extend it with mixin’s functionality. Here is an example of building an object called superman using two mixins humanFactory and flyFactory. superman has characteristics of a human so he has an ability to cry, however unlike humans, he can fly. So, combining two different kind of abilities we can transform an ordinary reporter clark kent into the superman.
Note: When you pass an empty object to this factory, the returning Object would have a functionality of humanfactory, flyFactory and their preserved states.
function mixin is one of the functional programming paradigm . Mixins help you reduce repetition of functions and promotes the reusability. This can reduce maintenance. It also support encapsulation using closures, with ability to inherit private data. In a way you can sort of achieve multiple inheritance since can inherit from multiple mixins. In this article, we discussed function mixins for a functional programming paradigm. The same concept also applies to ES2015 classes with a difference in syntax. To understand mixin for ES2015 classes, click here -> (class mixins coming soon).