Question

I wanted to be able to get a list of all variables in the current scope. I know it may not be possible (ex. 1, 2, 3 but it would really be helpful in simplifying a parsing algorithm for a Node/browser library I'm currently working on.

One thing: it doesn't need to be printed or safe from 'minification'.

I was wanting to be able to figure out what variables were introduced by reading a JS library and dynamically evaling it, finding the difference in state between the two. I know this approach sounds terrible on paper (I'm well acquainted with the hatred of eval), but if there is a better way to find this than just simply parsing the whole library (which is slow for any language other than C/etc.), I'm all ears.


For you all right off crying over the blatant use of eval, I know to use closures to protect the parent scope from modification. I also will be able to prevent changes to the browser display in the eval as well if it is in a browser environment (temporarily change some DOM constructors).

Était-ce utile?

La solution

Yes and no. "No" in almost every situation. "Yes," but only in a limited manner, if you want to check the global scope. Take the following example:

var a = 1, b = 2, c = 3;

for ( var i in window ) {
    console.log(i, typeof window[i], window[i]);
}

Which outputs, amongst 150+ other things, the following:

getInterface function getInterface()
i string i // <- there it is!
c number 3
b number 2
a number 1 // <- and another
_firebug object Object firebug=1.4.5 element=div#_firebugConsole
"Firebug command line does not support '$0'"
"Firebug command line does not support '$1'"
_FirebugCommandLine object Object
hasDuplicate boolean false

So it is possible to list some variables in the current scope, but it is not reliable, succinct, efficient, or easily accessible.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top