获取所有 Javascript 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2762075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:49:34  来源:igfitidea点击:

Get all Javascript Variables?

javascriptvariablesglobal-variables

提问by Matrym

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?

javascript 有没有办法检测所有分配的变量?例如,如果一个 js 文件创建了一堆 vars(全局范围),后续文件是否可以在不知道它们的名称以及哪些可能存在的情况下获取所有 vars?

Thanks in advance :)

提前致谢 :)

EDIT, Question Part 2:

编辑,问题第 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]
}

回答by

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

Flanagan 的“JavaScript - The Definitive Guide”在第 653 页给出了以下内容:

var variables = ""
for (var name in this)
    variables += name + "\n";

回答by Garrett

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

对于 Firefox,您可以看到 DOM 选项卡——虽然简单,但不能回答您的问题。

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

for inKinopiko 的答案中提供的循环将起作用,但在 IE 中不起作用。更多内容在下面链接的文章中进行了解释。

For IE, use the RuntimeObject.

对于 IE,请使用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:

也可以看看:

回答by Sammy

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

this变量。这是一个对象或数组,您可以简单地放置:

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

Unfortunately, it will return everythingunder the thisobject.

不幸的是,它将返回对象下的所有内容this