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, 开发者_Go百科bar: function(){} }
>>>
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/.
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:
- Using
propertyIsEnumerable()orhasOwnProperty() - Attempting to
deletethe property (truemostly means user-created,falsemeans built-in, though this can be erratic) - Stripping members you know you don't want through some other filtering array
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)
加载中,请稍侯......
精彩评论