如何获取当前作用域中定义的所有变量的列表? [英] How to get list of all variables defined in the current scope?
问题描述
我希望能够获得当前范围内所有变量的列表.我知道这可能是不可能的(例如 1、2, 3 但它确实有助于简化节点/浏览器库的解析算法我'我目前正在工作.
I wanted to be able to get a list of all variables in the current scope. I know it may not be possible (ex. 1, 2, 3 but it would really be helpful in simplifying a parsing algorithm for a Node/browser library I'm currently working on.
一件事:它不需要被打印出来,也不需要缩小".
One thing: it doesn't need to be printed or safe from 'minification'.
我希望能够通过读取 JS 库并动态地eval
来找出引入了哪些变量,找出两者之间的状态差异.我知道这种方法在纸面上听起来可怕(我很熟悉 eval 的仇恨),但是如果有更好的方法来找到它,而不仅仅是简单地解析整个库(这对于除了 C/etc. 之外的任何语言),我全神贯注.
I was wanting to be able to figure out what variables were introduced by reading a JS library and dynamically eval
ing it, finding the difference in state between the two. I know this approach sounds terrible on paper (I'm well acquainted with the hatred of eval), but if there is a better way to find this than just simply parsing the whole library (which is slow for any language other than C/etc.), I'm all ears.
对于你对 eval
的公然使用而哭泣,我知道使用闭包来保护父作用域不被修改.如果它在浏览器环境中,我也将能够防止在 eval 中更改浏览器显示(临时更改一些 DOM 构造函数).
For you all right off crying over the blatant use of eval
, I know to use closures to protect the parent scope from modification. I also will be able to prevent changes to the browser display in the eval as well if it is in a browser environment (temporarily change some DOM constructors).
推荐答案
是和否.几乎在所有情况下都是不".是",但仅限于有限的方式,如果您想检查全局范围.以下面的例子:
Yes and no. "No" in almost every situation. "Yes," but only in a limited manner, if you want to check the global scope. Take the following example:
var a = 1, b = 2, c = 3;
for ( var i in window ) {
console.log(i, typeof window[i], window[i]);
}
在 150 多个其他内容中,输出以下内容:
Which outputs, amongst 150+ other things, the following:
getInterface function getInterface()
i string i // <- there it is!
c number 3
b number 2
a number 1 // <- and another
_firebug object Object firebug=1.4.5 element=div#_firebugConsole
"Firebug command line does not support '$0'"
"Firebug command line does not support '$1'"
_FirebugCommandLine object Object
hasDuplicate boolean false
所以可以列出当前作用域中的一些变量,但并不可靠、简洁、高效或易于访问.
So it is possible to list some variables in the current scope, but it is not reliable, succinct, efficient, or easily accessible.
这篇关于如何获取当前作用域中定义的所有变量的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!