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 s开发者_开发技巧ure 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.
Since 1.11.2, Firebug's command line includes a syntax extension for getting the value of foo
: this.method.%foo
.
The whole closure can also be inspected, by turning on the "Show Closures" option in the DOM panel and expanding the "(closure)" pseudo-property of this.method
. This also works in Chrome (there the pseudo-property is called <function scope>
; there is no pref for it).
Maybe JavaScript doesn't implement it by default but i can imagine a way reading all properties from global Object (as foo is a property of it) and read every property till get to the closure, though this would be really slow. I must say i don't know much about javascript and maybe i'm just saying noncences, but maybe you get a new idea from my approach.
精彩评论