开发者

Is it possible to iterate over all properties in a JavaScript closure?

开发者 https://www.devze.com 2023-03-25 11:56 出处:网络
for ( var i in this ) { console.log(i); } With this loop, I iterate over all properties of an object.Is 开发者_运维百科it possible to find what local/closure variables exist?No, there\'s no way to e
for ( var i in this ) { console.log(i); }

With this loop, I iterate over all properties of an object. Is 开发者_运维百科it possible to find what local/closure variables exist?


No, there's no way to examine the contents of a scope, because there's no way to get a handle to it. (The global scope is excepted, because there are ways of getting a handle to it.)

What I mean by that is that there's no way to get the runtime to give you a reference to the scope as if it were a JavaScript object. Thus, there's no way to explore the properties; there's nothing for the right-hand side of a "for ... in" loop, in other words.

edit — if one could do this, it would allow for some interesting coding techniques. One could write utility functions, like the new-ish ".bind()" method on the Function prototype, so that the function returned would be able to check for certain special variables in the closure scope, for debugging or logging or other purposes. Thus services that manufacture functions could do some more "powerful" things based on the nature of the client environment. (I don't know of a language that would allow that.)

0

精彩评论

暂无评论...
验证码 换一张
取 消