This is a useful example of how you can augment a Class to have a particular method but not by using strict inheritance or by duplicating the relevant code for each Class you have. I came across this technique (known as “Mixin Classes”) while reading the book “Pro JavaScript Design Patterns”.
In the following code example we have a ‘Person’ Class which has no methods.
We also have another Class called ‘Mixin’ which has three methods.
We will augment the ‘Person’ Class so it has access to two of the three methods within the ‘Mixin’ Class.
I’ve not put any further details as the code should be self-explanatory. Otherwise I suggest you purchase the book “Pro JavaScript Design Patterns” to help yourself understand what the code does and why.
/* Person Class */ var Person = function(settings) { this.name = settings.name || 'no name given'; this.age = settings.age || 'no age given'; }; /* Mixin Class */ var Mixin = function(){}; Mixin.prototype = { doSomething1: function() { alert('do something 1!'); }, doSomething2: function() { alert('do something 2!'); }, doSomething3: function() { alert('do something 3!'); } }; // Function to augment an existing class with a method(s) from another class function augment(receivingClass, givingClass) { // Only give certain methods if (arguments[2]) { for (var i=0, len=arguments.length; i<len; i++) { receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]]; } } // Give all methods found else { for (methodName in givingClass.prototype) { // A quick check to make sure the receiving class doesn't already have a method of the same name as what's currently being processed if (!receivingClass.prototype[methodName]) { receivingClass.prototype[methodName] = givingClass.prototype[methodName]; } } } } // Augment the Person class to have the methods 'doSomething1' and 'doSomething3' /* We can also do... augment(Person, Mixin); ...so the 'Person' class receives ALL methods within 'Mixin'. */ augment(Person, Mixin, 'doSomething1', 'doSomething3'); // Create a new Person var employee = new Person({name:'John Smith', age:27}); // Test to make sure we have access to the relevant methods employee.doSomething1(); employee.doSomething3(); // Just to prove we aren't copying all the methods from the 'Mixin' Class... try { employee.doSomething2(); } catch(e) { alert(e.message); }