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?
No, unfortunately there is no way to access a non-global scope similar to how
window[...]works.However, depending on what you need to do using an object instead of a native scope would be a good idea.