简体   繁体   English

如何检查javascript中的绑定闭包变量?

[英]How to inspect bound closure variables in javascript?

Suppose we do something like this (as part of the construction of a Javascript object):假设我们做这样的事情(作为构建 Javascript 对象的一部分):

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 .现在将生成一个闭包以确保保留foo并可在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 .我正在寻找的是一种枚举method中可用的所有变量的method ,其中应包括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?是否有可能做到这一点?

Since 1.11.2, Firebug's command line includes a syntax extension for getting the value of foo : this.method.%foo .从 1.11.2 开始,Firebug 的命令行包括用于获取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 .也可以通过打开 DOM 面板中的“Show Closures”选项并展开this.method的“(closure)”伪属性来检查整个闭包。 This also works in Chrome (there the pseudo-property is called <function scope> ; there is no pref for it).这也适用于 Chrome(伪属性被称为<function scope> ;它没有首选项)。

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).事实上,隐藏在 JavaScript 闭包中的数据是少数真正真正私有的数据之一(与 C#、C++、Java 等中的“私有”数据相反,它们总是可以通过指针魔法或反射访问)。

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).您可能希望的是一个内置于主要 JavaScript 解释器之一的工具(或者至少是将此类工具插入核心引擎的内置功能)。 One in Firefox/Firebug or V8/Node.js would be nice, but I believe that we're out of luck at the moment. Firefox/Firebug 或 V8/Node.js 中的一个会很好,但我相信我们现在不走运。

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.也许 JavaScript 默认没有实现它,但我可以想象一种从全局对象读取所有属性的方法(因为 foo 是它的一个属性)并读取每个属性直到到达闭包,尽管这会很慢。 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.我必须说我对 javascript 不太了解,也许我只是在说 noncence,但也许你从我的方法中得到了一个新的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM