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

How the question arises - is it possible to get the names of all the variables declared in the current namespace? For example, something like this:

  >>> var x = 42;
 >>> function bar () {...}
 >>> getNamespace ()
 {x: 42, bar: function () {}}
 >>>
+4
source share
3 answers

Not possible in most implementations. Although in Rhino you can get 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]] 

See http://dmitrysoshnikov.com/ecmascript/chapter-2-variable-object/ for more details.

+2
source
 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 are in a global scope (for example, a window object). It will also return inline and prototype methods. You can curb this:

  • Using propertyIsEnumerable() or hasOwnProperty()
  • Attempting to delete property ( true basically means creating a user, false means inline, although this may be unstable)
  • Disabling members that you know you don't need through some other filtering array
0
source

You can get the source of the current scope, for example:

 arguments.callee.toString() 

So, I assume that you can parse this line by matching things like "var" and "function", corresponding from then to ";" or "}"

But that would be a very dirty, rude approach! If you really need to get such information, you better not create variables at all - define each value and function as a property of an object, then you can just iterate over them with (key in obj)

-1
source

All Articles