I am writing some JavaScript profiling bits and need to be able to intercept methods inside a closure.
I managed to get this working:
var t = (function() {
var echo = function(v) { console.log("calling echo with " + v); };
return {
intercept: function(n, f) {
var old = eval(n);
var newFunction = (function(that, old){
return f(that, old);
})(this, old);
eval(n + " = newFunction ");
},
getEchoFunction: function() { return echo; }
};
})();
var c = t.getEchoFunction();
c("hello");
t.intercept("echo", function(that,old){
return function() {
console.log("before echo");
old.apply(that,arguments);
console.log("after echo");
};
});
c = t.getEchoFunction();
c("world");
Output is:
"calling echo with hello" "before echo" "calling echo with world" "after echo"
So, this "intercept" API lets me intercept and re-write function declarations hidden in a closure.
However, there is much complaining about eval in the world.
Is there any way to write the same API without needing to use eval in the intercept function?
this[n] = newFunction? But if there isn't another way to do it, this seems like a legitimate use ofevalanyways.thispoints to the global object, is undefined/null (strict mode) or points to an object - but never to another scope.