简体   繁体   中英

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 .

I quite like the Firebug extension on Firefox.

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.

Firebug DOM选项卡

You can use browser extension that helps with such things like:

-Firebug extension in Firefox

-Developer Tools window in Chrome

-Dragonfly in Opera

I used this regex to show me all the javascript variables in my project code.

[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).

For me, I used Sublime Text 2's awesome multi-file search by allowing regex and disabling the context around the match. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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