简体   繁体   English

如何在JavaScript中搜索全局变量

[英]How to search global variables in JavaScript

是否有任何工具或正则表达式可能有助于获取JavaScript项目中所有全局变量的列表?

You can loop through the window object for querying all globally defined data (variables and functions, including predefined ones): 您可以遍历窗口对象以查询所有全局定义的数据(变量和函数,包括预定义的数据):

for (var key in window) {
    console.log(key + "=" + window[key]);
}

For analysing the source code, use JSLint . 要分析源代码,请使用JSLint

I quite like the Firebug extension on Firefox. 我非常喜欢Firefox上的Firebug扩展。

Here is the DOM tab enumerating all the properties in the Global (ie. window) object and colouring them by type, these are essentially your global variables. 这是DOM选项卡枚举全局(即窗口)对象中的所有属性并按类型着色,这些基本上是您的全局变量。

Firebug DOM选项卡

You can use browser extension that helps with such things like: 您可以使用浏览器扩展来帮助执行以下操作:

-Firebug extension in Firefox -Firebug在Firefox中的扩展

-Developer Tools window in Chrome Chrome中的“开发者工具”窗口

-Dragonfly in Opera -Dragonfly在Opera中

I used this regex to show me all the javascript variables in my project code. 我用这个正则表达式向我展示了项目代码中的所有javascript变量。

[a-zA-Z0-9]* = .*;

Then I visually scanned the matches to make sure that all my variables were not global. 然后我直观地扫描了比赛,以确保我的所有变量都不是全局变量。 (ie there were 'vars' next to them, so long as they were not parameters passed to a function). (即它们旁边有'vars',只要它们不是传递给函数的参数)。

For me, I used Sublime Text 2's awesome multi-file search by allowing regex and disabling the context around the match. 对我来说,我通过允许正则表达式和禁用匹配的上下文来使用Sublime Text 2的令人敬畏的多文件搜索。 I also told the search to only search in the folder containing my own javascript files, so it would not show variables from other frameworks or languages. 我还告诉搜索只搜索包含我自己的javascript文件的文件夹,因此它不会显示来自其他框架或语言的变量。 That made it so that every variable appeared one after the other, and it was a ton easier to see any global variable leaks. 这使得每个变量一个接一个地出现,并且更容易看到任何全局变量泄漏。

Hope this helps and wasn't too confusing. 希望这有所帮助,而不是太混乱。 I'm a regex newb but this worked for me. 我是一个正则表达新手,但这对我有用。 I already found 3 global leaks in my own project in about 5 minutes. 我已经在大约5分钟内在我自己的项目中发现了3个全局泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM