JSFiddle - React, Tailwind, and code Playground
by andyw_
JavaScript
/*The Mixin Pattern*/
/* This Pattern allows passing of different arguments to extend an existing classes function using another similar class.
This Pattern is useful for dynamically adding functionality to a base object/class, this pattern is also used by jQuery for allowing plugins to be developed, these plugin functionalities are instantiated dynamically, adding/modifying/creating from core JavaScript and jQuery functionalities */
/* Car Class */
var Car = function(settings){
this.model = settings.model || 'no model provided';
this.colour = settings.colour || 'no colour provided';
};
/* Mixin Class */
var Mixin = function(){};
Mixin.prototype = {
driveForward: function(){
console.log('drive forward');
},
driveBackward: function(){
console.log('drive backward');
}
};
/* Augment existing class with a method from another class */
function augment(receivingClass, givingClass) {
/* only provide certain methods */
if (arguments[2]) {
for (var i=2, len=arguments.length; i<len; i++) {
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
}
/* provide all methods*/
else {
for (var methodName in givingClass.prototype) {
/* check to make sure the receiving class doesn't
have a method of the same name as the one currently
being processed */
if (!receivingClass.prototype[methodName]) {
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
}
}
}
/* Augment the Car class to have the methods 'driveForward' and 'driveBackward'*/
augment(Car, Mixin,'driveForward','driveBackward');
/* Create a new Car */
var vehicle = new Car({model:'Ford Escort', colour:'blue'});
/* Test to make sure we now have access to the methods*/
vehicle.driveForward();
vehicle.driveBackward();