A mixin is a collection of functionality, defined as methods and variables in an object, which may be included in multiple classes such that each class gains that functionality. A mixin itself is not capable of being instantiated.
A mixin is defined as an object. For example, the following mixin is defined to include a method toDebugString()
which will create a string based on the values of all variables in an instance of a class:
var DebugString = { toDebugString: function() { var out = ""; for (var i in this) { if (!(this[i] instanceof Function)) { out += i + " = " + this[i].toString() + "\n"; } } } };
The mixin can then be included in classes defined using the $include
property in Core.extend()
. The value of the $include
property is a Array
of mixins:
MixinExample = Core.extend({ $include: [DebugString], instanceVariable1: "foo", instanceVariable2: "oof", instanceMethod1: function() { return this.instanceVariable1 + this.instanceVariable2; } });
By "mixing in" or mixin object, we are now able to invoke toDebugString()
on instances of MixinExample
.
It is important to note that a mixin will never override an existing property of a class. If for example, we had already defined a toDebugString()
method in MixinExample
, the version from the DebugString
mixin would not be added.
In the case where multiple mixins are specified in the $include
array, there is the possibility that multiple mixins will define the same properties to be mixed-in to the class. In such a case, a mixin specified later in the array will override that defined earlier in the array.