The term mixin is usually used to specify a collection of functions available to be shared among objects or classes. It can be somehow considered similar to abstract classes in classical OOP languages. Usually, the mixin functions are not directly used, but they are borrowed to others objects or classes in order to extend them without creating a strict relationship as it could be with inheritance. Let's introduce mixins in JavaScript with a simple example.
Consider our Person()
constructor function in its minimal implementation:
function Person(name, surname) { this.name = name; this.surname = surname; }
Then consider a simple object literal implementing a getFullName()
method that returns the full name based on the existing name
and surname
properties:
var myMixin = { getFullName: function() { return this.name + " " + this.surname; } };
This object is our mixin. It implements a generic function, not bound to a specific object...