如何检查 JavaScript 中绑定的闭包变量?
假设我们做了这样的事情(作为构造 Javascript 对象的一部分):
var foo = 3;
this.method = function () { alert(foo); };
现在将生成一个闭包以确保保留 foo
并可在 method
中使用。有没有办法对当前的关闭进行内省?
我正在寻找的是一种枚举 method
内可用的所有变量的方法,其中应包括 foo
。像这样的调试代码将极大地帮助调试闭包的绑定,但我还没有找到它。可以这样做吗?
Suppose we do something like this (as part of the construction of a Javascript object):
var foo = 3;
this.method = function () { alert(foo); };
Now a closure will be generated to make sure foo
is retained and available for use in method
. Is there a way to do introspection on the current closure?
What I'm looking for is a way to enumerate all the variables that are available inside method
, which should include foo
. Debug code like this would greatly help in debugging the binding of closures, but I have yet to find it. Is it possible to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
语言本身不包含这种可能性。事实上,隐藏在 JavaScript 闭包中的数据是少数真正真正私有的数据之一(与 C#、C++、Java 等中的“私有”数据相反,这些数据始终可以通过指针魔法或反射进行访问)。
简而言之,这将是编译器级别的事情。您可能希望有一个内置于主要 JavaScript 解释器之一的工具(或者至少具有将此类工具插入核心引擎的内置功能)。 Firefox/Firebug 或 V8/Node.js 中的一个会很好,但我相信我们现在运气不好。
The language itself contains no such possibilities. In fact, data hidden in JavaScript closures are one of the few things that are actually truly private (as opposed to "private" data in C#, C++, Java etc, that can always be accessed with pointer magic or reflection).
In short, this would be a compiler-level thing. What you could hope for is a tool built-in to one of the major JavaScript-interpreters (or at least built-in capability to plug such a tool into the core engine). One in Firefox/Firebug or V8/Node.js would be nice, but I believe that we're out of luck at the moment.
从 1.11.2 开始,Firebug 的命令行包含用于获取
foo
值的语法扩展:this.method.%foo
。还可以通过打开 DOM 面板中的“Show Closures”选项并展开
this.method
的“(closure)”伪属性来检查整个闭包。这在 Chrome 中也适用(其中伪属性称为
;没有它的首选项)。Since 1.11.2, Firebug's command line includes a syntax extension for getting the value of
foo
:this.method.%foo
.The whole closure can also be inspected, by turning on the "Show Closures" option in the DOM panel and expanding the "(closure)" pseudo-property of
this.method
. This also works in Chrome (there the pseudo-property is called<function scope>
; there is no pref for it).也许 JavaScript 默认情况下没有实现它,但我可以想象一种从全局对象读取所有属性(因为 foo 是它的属性)并读取每个属性直到到达闭包的方法,尽管这会非常慢。我必须说我对 javascript 了解不多,也许我只是在胡说八道,但也许你会从我的方法中得到一个新的想法。
Maybe JavaScript doesn't implement it by default but i can imagine a way reading all properties from global Object (as foo is a property of it) and read every property till get to the closure, though this would be really slow. I must say i don't know much about javascript and maybe i'm just saying noncences, but maybe you get a new idea from my approach.