Skip to content

Instantly share code, notes, and snippets.

@acutmore
Created September 7, 2016 17:24
Show Gist options
  • Save acutmore/59a32e7e5b0664630c83c4079bb02ed5 to your computer and use it in GitHub Desktop.
Save acutmore/59a32e7e5b0664630c83c4079bb02ed5 to your computer and use it in GitHub Desktop.
Basic es5 proxy
console.clear();
function isFunction(o){
return typeof o === (typeof isFunction);
}
/**
* Wraps up an object replacing methods with an interceptor
* @param obj - the obj to wrap
* @param interceptor {(obj, methodName, args) => any}
* @returns the proxy
*/
function createProxy(obj, interceptor){
var newObj = Object.create(obj);
var layer = obj;
var keys = [];
while (layer){
keys = keys.concat(Object.getOwnPropertyNames(layer));
layer = Object.getPrototypeOf(layer);
}
keys.forEach(function(prop){
if (isFunction(obj[prop])){
newObj[prop] = function(){
return interceptor(obj, prop, arguments);
};
}
});
return newObj;
}
var object = ({
foo: function(){
return "bar";
}
});
var proxy = createProxy(object, function(obj, methodName, args){
console.log(methodName + " called");
return obj[methodName].apply(obj, args);
});
console.log( proxy.foo() );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment