开发者

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

开发者 https://www.devze.com 2023-01-12 02:08 出处:网络
As the question suggests — is it possible to get the names of all variables declared in the current namespace? For example, something like this:

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:

  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


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消