Skip to content

Instantly share code, notes, and snippets.

@ElliotChong
Created September 4, 2012 17:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ElliotChong/3624204 to your computer and use it in GitHub Desktop.
Save ElliotChong/3624204 to your computer and use it in GitHub Desktop.
JavaScript implementation of a Proxy class.
/**
* JavaScript implementation of a Proxy class.
**/
​function Proxy(p_target)
{
var self = this;
self.target = p_target;
// Access target's properties
self.get = function (p_property)
{
return self.target[p_property];
}
self.set = function (p_property, p_value)
{
self.target[p_property] = p_value;
}
// Proxy target's functions
for (var key in self.target)
{
if (typeof self.target[key] === 'function')
{
self[key] = function ()
{
return self.target[key].apply(self.target, arguments);
}
}
}
}
Proxy.prototype = new Object();​
Copy link

ghost commented Aug 6, 2015

Line 25 needs a closure for private scope, otherwise all the functions are assigned to the latest proxied function.

Here is how I put it together

self[key] = (function (localKey)
{
    return function() { return self.target[localKey].apply(self.target, arguments); };
})(key);

Thanks for sharing your code!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment