David Wolever
David Wolever

Reputation: 154634

JavaScript: is it possible to get the content of the current namespace?

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(){} }
>>>

Upvotes: 4

Views: 3201

Answers (3)

brothercake
brothercake

Reputation: 51

You can get the source of the current function scope, like this:

arguments.callee.toString()

So I suppose you could parse that string, matching things like "var " and "function ", matching from then until ";" or "}"

But that would be a very very messy, brute-force approach! If you really need to get this kind of information, you'd be better off not creating variables at all -- define every value and function as an object property, then you can simply iterate through them with for(key in obj)

Upvotes: -1

matyr
matyr

Reputation: 5774

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/.

Upvotes: 2

sevenflow
sevenflow

Reputation: 777

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

Upvotes: 0

Related Questions