views:

73

answers:

2

As the question suggests — is it possible to get the names of all variables declared in the current namespace? For example, something like this:

>>> var x = 42;
>>> function bar() { ...}
>>> getNamespace()
{ x: 42, bar: function(){} }
>>>
A: 
function listMembers (obj) {
    for (var key in obj) {
        console.log(key + ': ' + obj[key]);
    }
}

// get members for current scope
listMembers(this);

This can get a little hairy if you're in the global scope (eg. the window object). It will also return built-in and prototypical methods. You can curb this by:

  1. Using propertyIsEnumerable() or hasOwnProperty()
  2. Attempting to delete the property (true mostly means user-created, false means built-in, though this can be erratic)
  3. Stripping members you know you don't want through some other filtering array
sevenflow
Unfortunately this does not work. Consider: `function foo(){ var bar = 42; listMembers(this); }` — in this case, `this` is not at all related to the definition of `bar`.
David Wolever
+2  A: 

Impossible in most implementations. Though in Rhino, you can reach to the activation object via __parent__.

js> function f(){ var x,y=1; return (function(){}).__parent__ }
js> uneval([v for(v in Iterator(f()))])
[["arguments", {}], ["x", , ], ["y", 1]]

For details, see http://dmitrysoshnikov.com/ecmascript/chapter-2-variable-object/.

matyr