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(){} }
>>>
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(){} }
>>>
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:
propertyIsEnumerable() or hasOwnProperty()delete the property (true mostly means user-created, false means built-in, though this can be erratic)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/.