2
for ( var i in this ) { console.log(i); }

With this loop, I iterate over all properties of an object. Is it possible to find what local/closure variables exist?

Upperstage
  • 3,747
  • 8
  • 44
  • 67

1 Answers1

3

No, there's no way to examine the contents of a scope, because there's no way to get a handle to it. (The global scope is excepted, because there are ways of getting a handle to it.)

What I mean by that is that there's no way to get the runtime to give you a reference to the scope as if it were a JavaScript object. Thus, there's no way to explore the properties; there's nothing for the right-hand side of a "for ... in" loop, in other words.

edit — if one could do this, it would allow for some interesting coding techniques. One could write utility functions, like the new-ish ".bind()" method on the Function prototype, so that the function returned would be able to check for certain special variables in the closure scope, for debugging or logging or other purposes. Thus services that manufacture functions could do some more "powerful" things based on the nature of the client environment. (I don't know of a language that would allow that.)

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • +1, the only exception I know is Rhino, which provides a way to access the top-most object in the scope chain, e.g.: `var scope = function () {}.__parent__;` – Christian C. Salvadó Aug 03 '11 at 18:05
  • Ah yes, thanks, I remember reading that some time ago and not really understanding what they were talking about :-) – Pointy Aug 03 '11 at 18:05
  • The Chrome and FireBug debuggers allow one to probe into closures; I suspect add-ons have an advantage not provided by the language? – Upperstage Aug 03 '11 at 18:07
  • Well the add-ons get access to browser internals; clearly the interpreter itself knows how to mess with activation objects :-) I don't know the specifics of what those debugger environments do. – Pointy Aug 03 '11 at 18:09