是否有一种方法来获得目前在javascript范围内的所有变量?


当前回答

你不能。

变量,函数声明的标识符和函数代码的参数,被绑定为变量对象的属性,这是不可访问的。

参见:

作用域链和标识符解析

其他回答

不。“作用域内”变量由“作用域链”决定,不能通过编程方式访问。

有关详细信息(相当多),请查看ECMAScript (JavaScript)规范。这里有一个官方页面的链接,你可以在那里下载规范规范(PDF格式),这里有一个官方的,可链接的HTML版本。

根据您对Camsoft的评论进行更新

The variables in scope for your event function are determined by where you define your event function, not how they call it. But, you may find useful information about what's available to your function via this and arguments by doing something along the lines of what KennyTM pointed out (for (var propName in ____)) since that will tell you what's available on various objects provided to you (this and arguments; if you're not sure what arguments they give you, you can find out via the arguments variable that's implicitly defined for every function).

所以除了你定义函数的作用域之外,你还可以通过其他方法找到其他可用的函数:

var n, arg, name;
alert("typeof this = " + typeof this);
for (name in this) {
    alert("this[" + name + "]=" + this[name]);
}
for (n = 0; n < arguments.length; ++n) {
    arg = arguments[n];
    alert("typeof arguments[" + n + "] = " + typeof arg);
    for (name in arg) {
        alert("arguments[" + n + "][" + name + "]=" + arg[name]);
    }
}

(你可以进一步了解更多有用的信息。)

不过,我可能会使用Chrome的开发工具(即使你通常不使用Chrome进行开发)或Firebug(即使你通常不使用Firefox进行开发),或Opera上的Dragonfly,或IE上的“F12开发工具”之类的调试器。并通读它们提供的任何JavaScript文件。然后打他们的头找个合适的医生。: -)

你不能。

变量,函数声明的标识符和函数代码的参数,被绑定为变量对象的属性,这是不可访问的。

参见:

作用域链和标识符解析

是也不是。几乎在任何情况下都说“不”。“是的”,但如果您想检查全局作用域,则只能以有限的方式进行。举个例子:

var a = 1, b = 2, c = 3;

for ( var i in window ) {
    console.log(i, typeof window[i], window[i]);
}

在150多个其他东西中,输出如下:

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

因此,可以在当前范围内列出一些变量,但它不可靠、不简洁、不高效或不容易访问。

一个更好的问题是,为什么要知道作用域内的变量是什么?

正如大家所注意到的:你不能。 但是你可以创建一个obj并将你声明的每个var赋值给那个obj。 这样你就可以很容易地检查你的vars:

var v = {}; //put everything here

var f = function(a, b){//do something
}; v.f = f; //make's easy to debug
var a = [1,2,3];
v.a = a;
var x = 'x';
v.x = x;  //so on...

console.log(v); //it's all there

访问特定范围内Vars的最简单方法

打开开发人员工具>资源(Chrome) 打开具有该范围的函数的文件(提示cmd/ctrl+p来查找文件) 在该函数中设置断点并运行代码 当它停在断点时,您可以通过控制台(或范围变量窗口)访问范围变量。

注意:你想对未最小化的js做这个操作。

显示所有非私有变量的最简单方法

打开控制台(Chrome) 类型:this.window 回车

现在你将看到一个对象树,你可以展开所有已声明的对象。