Get all Javascript Variables?

前端 未结 4 1614
感情败类
感情败类 2020-12-05 03:30

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

相关标签:
4条回答
  • 2020-12-05 03:39

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

    var variables = ""
    for (var name in this)
        variables += name + "\n";
    
    0 讨论(0)
  • 2020-12-05 03:41

    This will output all the variables into the console without needing to read the variable yourself.

    var variables = ""
    for (var name in this)
        variables += name + "\n";
    console.log(variables)
    
    /*
    This could work too... but it's such a big unecessary code for something you could do in one line 
    var split = variables.split("\n");
    for (var i in split)
        console.log(split[i])
    */

    0 讨论(0)
  • 2020-12-05 03:48

    There is the this variable. This is an object or an array, and you can simply put:

    for(i in this) { //do something }
    

    Unfortunately, it will return everything under the this object.

    0 讨论(0)
  • 2020-12-05 04:00

    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:

    • Detecting Global Pollution with the JScript RuntimeObject (DHTML Kitchen article)
    • RuntimeObject (MSDN docs)
    0 讨论(0)
提交回复
热议问题