Skip to content

Instantly share code, notes, and snippets.

@purplecabbage
Created March 4, 2011 10:35
Show Gist options
  • Save purplecabbage/854437 to your computer and use it in GitHub Desktop.
Save purplecabbage/854437 to your computer and use it in GitHub Desktop.
Non-Inheritance addition of methods from a source class, either to an instance or a prototype
/*
@destObj :Object to decorate
@propName :String name of
@className :Class to use as the decorator source
*/
function decorate(destObj,propName,className)
{
// are we working with an instance?
if(typeof destObj == "object")
{
var tmp = destObj[propName] = new className();
for(var v in tmp)
{
if(typeof tmp[v] == "function")
{
destObj[v] = function(){return tmp[v].apply(tmp,arguments);};
}
}
}
// working with prototypes
else if(typeof destObj == "function")
{
var src = className.prototype;
var dest = destObj.prototype;
for(var v in src)
{
if(typeof src[v] == "function")
{
dest[v] = function()
{
var self = this;
if(!self[propName])
{
self[propName] = new className();
}
return self[propName][v].apply(self[propName],arguments);
};
}
}
}
}
// Sample Use
var MixInClass = function(){};
MixInClass.prototype.doSomething = function(blah)
{
console.log("I am doing something with blah :: " + blah);
}
var Descendant = function(){};
var Descendant2 = function(){};
// Decorate an instance of an object with the methods of another class
var bob = new Descendant();
decorate(bob,"_prop",MixInClass);
bob.doSomething("bob");
// Decorate a class with the methods of another class
decorate(Descendant2,"_prop",MixInClass);
var joe = new Descendant2();
joe.doSomething("joe");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment