2

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?

2
  • 1
    What happens if you use this[n] = newFunction? But if there isn't another way to do it, this seems like a legitimate use of eval anyways. Commented Nov 18, 2012 at 23:23
  • 1
    this points to the global object, is undefined/null (strict mode) or points to an object - but never to another scope. Commented Nov 18, 2012 at 23:24

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It sure would have been handy in javascript for cases like this if there was a pre-defined symbol for the local scope so one could access all local variables off that object.
Indeed, but it doesn't seem to be very common unfortunately. Even in Python they did not add a way to access such a scope until lately (nonlocal in py3k)
I am pretty sure Perl has this as well, Ruby are resistant to adding cleaner way of exposing bindings further up the stack

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.