Created
September 7, 2016 17:24
-
-
Save acutmore/59a32e7e5b0664630c83c4079bb02ed5 to your computer and use it in GitHub Desktop.
Basic es5 proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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