拦截javascript中的全局变量定义
我正在尝试整理一些 javascript 代码,其中一个步骤是删除所有无用的(或完全错误的)全局变量,这些变量是从以下错误中滑入的:
for (prop in obj) { ...
而不是
for (var prop in obj) { ...
JSLint 有助于找出这种讨厌的情况,但它不是当运行时发生令人讨厌的事情时,100%万无一失。 我已经尝试添加一些监视代码,如果检测到某些新变量,这些代码会定期检查控制台的全局范围日志记录,这有助于更多,但是当它告诉我一个名为“的新全局变量”时i" 已被检测到......好吧,在数千行代码中找出发生的地方是一团糟。
那么我们来了:有没有更好的方法/工具/脚本/什么来找到小害虫? 我的梦想是像 Firebug 插件一样,每当创建新的全局变量时就会停止执行...
谢谢!
I'm trying to tidy up some javascript code and one of the steps is removing all useless (or plain wrong) global variables that have slipped in from errors like:
for (prop in obj) { ...
instead of
for (var prop in obj) { ...
JSLint helps a bit in finding out this nastiness, but it is not 100% foolproof when the nastiness happens at runtime.
I already tried to add some monitoring code that routinely checks the global scope logging to the console if some new variable is detected, and that helped some more, but when it tells me that a new global variable named "i" has been detected ... well, it's a mess finding out where that happened in thousands of lines of code.
So here we come: is there a better way/tool/script/whatever to find the little pests?
My dream is something like a Firebug plugin that stops the execution whenever a new global variable is created...
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可能会发现这个小书签很有用。
另外,请查看此答案:如何检测新全局变量的创建?< /a>
You may find this bookmarklet useful.
Also, checkout this answer: How to detect creation of new global variables?
您现在可以按照这个类似问题中的说明拦截变量定义
你将能够找到它的定义位置
You can now intercept variable definition as explained on this similar question
and you'll be able to find where it was defined
我想知道您是否可以设置一个超时来创建所有全局变量的列表,然后将其与上次触发超时的时间进行比较。我在 Stack Overflow 上找到了这个,也许您可以将此代码与 setTimeout() 结合使用来获得您想要的。
Stack Overflow 链接:获取作用域内的所有变量
I wonder if you could set a timeout to create a list of all global variables and then compare that against the last time the timeout fired. I found this on Stack Overflow, and maybe you could use this code in conjunction with a setTimeout() to get what you want.
Stack Overflow link: Getting All Variables In Scope
好吧,我很久以前就写了这个,所以代码很糟糕,但它完成了工作:https://gist.github。 com/1132193
粘贴到 firebug 控制台或包含为脚本。
well, I wrote this long time ago, so code sucks, but it does the job: https://gist.github.com/1132193
paste in the firebug console or include as a script.
你说,你正在尝试整理一些代码。
在这种情况下 - 使用 IDE,例如 NetBeans PHP(免费)或 JetBrains WebStorm (30 美元)。它们都为全局变量着色,并且做了很多其他有用的事情;)
如果您的轮询脚本仍然会检测到全局变量的创建 - 追踪有问题的函数,并使它们受到影响;)最终,代码将变得干净。
You say, you are trying to tidy up some code.
In that case - use IDE, like NetBeans PHP (free) or JetBrains WebStorm (30$). They both color global variables, and do lots of other useful stuff ;)
If your polling script will still detect creation of global variables - trace down offending functions, and make them suffer ;) Eventually, the code will become clean.