获取范围内的所有变量 [英] Getting All Variables In Scope

查看:129
本文介绍了获取范围内的所有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法获取当前在javascript范围内的所有变量?

Is there a way to get all variables that are currently in scope in javascript?

推荐答案

没有。 在范围内变量由范围链确定,该范围链无法以编程方式访问。

No. "In scope" variables are determined by the "scope chain", which is not accessible programmatically.

有关详细信息(非常多),请查看ECMAScript( JavaScript)规范。 这是一个链接到官方页面,您可以在其中下载规范规范(PDF)和这里的一个官方可链接HTML版本。

For detail (quite a lot of it), check out the ECMAScript (JavaScript) specification. Here's a link to the official page where you can download the canonical spec (a PDF), and here's one to the official, linkable HTML version.

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

变量事件函数的范围取决于您定义事件函数的位置,而不是它们如何调用它。 但是,你可以通过这个找到有关你的功能可用的有用信息,并通过KennyTM指出的方式做一些事情( for(____中的var propName))因为这会告诉你提供给你的各种对象有什么可用( this 和参数;如果你不确定他们给你什么参数,你可以通过为每个函数隐式定义的 arguments 变量找到。

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

因此,除了您定义函数的位置之外,您还可以通过其他方式找到其他可用的内容:

So in addition to whatever's in-scope because of where you define your function, you can find out what else is available by other means by doing:

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]);
    }
}

(你可以扩展它以获得更多有用的信息。)

(You can expand on that to get more useful information.)

不过,我可能会使用像Chrome开发工具这样的调试器(即使你通常不使用Chrome进行开发)或 Firebug (即使你通常不使用Firefox进行开发),或Opera上的Dragonfly,或IE上的F12开发人员工具 。并阅读他们为您提供的任何JavaScript文件。并且为了正确的文档而击败他们。 : - )

Instead of that, though, I'd probably use a debugger like Chrome's dev tools (even if you don't normally use Chrome for development) or Firebug (even if you don't normally use Firefox for development), or Dragonfly on Opera, or "F12 Developer Tools" on IE. And read through whatever JavaScript files they provide you. And beat them over the head for proper docs. :-)

这篇关于获取范围内的所有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆