views:

82

answers:

2

Is there a way for javascript to detect all assigned variables? For example, if one js file creates a bunch of vars (globally scoped), can a subsequent file get all the vars without knowing what they're named and which might exist?

Thanks in advance :)

EDIT, Question Part 2:

How do I get the values of these variables? Here is what I have attempted:

This is what I ended up with, as per comment suggestions:

for (var name in this) {
    variables[name] = name;
    variables[name]=this[name]
}
+6  A: 

Flanagan's "JavaScript - The Definitive Guide" gives the following on page 653:

var variables = ""
for (var name in this)
    variables += name + "\n";
Kinopiko
Gives some extra stuff, presumably from the browser, but it works! Thanks :)
Matrym
Uh. Sorry, but could you help me understand how to get the values of each of these variables now? I added code to what I attempted..
Matrym
The "name" is like a key into a "this" hash. Get the value by this[name].
wombleton
Thanks wombleton. I'd love to actually use the variables as a key / value hash itself. Is that what "this" is if used entirely by itself?
Matrym
+1  A: 

For Firefox, you can see the DOM tab -- easy, though not an answer to your question.

The for in loop provided in Kinopiko's answer will work, but not in IE. More is explained in the article linked below.

For IE, use the RuntimeObject.

if(this.RuntimeObject){
    void function() {
        var ro = RuntimeObject(),
            results = [],
            prop;
        for(prop in ro) {
            results.push(prop);
        }
        alert("leaked:\n" + results.join("\n"));
    }();
}

See also:

Garrett
Hi Garrett. I've edited your answer to add code formatting to the `RuntimeObject` example.
Tim Down