First of all, I had to extend the function prototype so I could modify the class' prototype before actually using it. I could have done this in the constructor, but that would mean it runs every time you create a new instance of the class. Hardly ideal.
Code: Select all
Function.prototype.makeProxyFor = function (instanceClass)
{
for (var i in instanceClass.prototype)
{
eval ("this.prototype['"+i+"'] = function () { return this.instance['"+i+"'].apply (this.instance, arguments); } ")
}
}
Code: Select all
function Proxy ()
{
this.instance = new Something ();
}
function Something ()
{
}
Something.prototype.hello = function ()
{
alert ('Hello from the proxied class!')
}
Proxy.makeProxyFor (Something)
test = new Proxy ()
test.hello ()
Thats not exactly the best example, as I could have done that by making Proxy inherit from Something, but you get the idea.
A better real world example would be the menu system I'm working on currently - I have a MenuStructure class that only controls and keeps track of where items are in relation to itself within the menu (using recursion to make it an n-level menu), and then I have a proxy that is used to display the items on the page and control all the visual elements of it basically. It may seem a bit of a long way of doing things, but you'd be surprised at the number of different variations of menu I'm asked to do, this allows me to keep the same model for the structure but change the way it appears or behaves on-page.