Suppose we do something like this (as part of the construction of a Javascript object):
var foo = 3;
this.method = function () { alert(foo); };
Now a closure will be generated to make sure foo is retained and available for use in method. Is there a way to do introspection on the current closure?
What I’m looking for is a way to enumerate all the variables that are available inside method, which should include foo. Debug code like this would greatly help in debugging the binding of closures, but I have yet to find it. Is it possible to do this?
The language itself contains no such possibilities. In fact, data hidden in JavaScript closures are one of the few things that are actually truly private (as opposed to “private” data in C#, C++, Java etc, that can always be accessed with pointer magic or reflection).
In short, this would be a compiler-level thing. What you could hope for is a tool built-in to one of the major JavaScript-interpreters (or at least built-in capability to plug such a tool into the core engine). One in Firefox/Firebug or V8/Node.js would be nice, but I believe that we’re out of luck at the moment.