Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inspect bound closure variables in javascript?

Tags:

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?

like image 506
Ruben Vermeersch Avatar asked Jan 31 '11 09:01

Ruben Vermeersch


People also ask

Where are closures stored in JavaScript?

How do JavaScript closures work? At the virtual machine level, every function has its own lexical environment which keeps track of this information. The virtual machine finds which variables are accessed in closures and stores them on the heap, and they live for as long as any closure might need them.

What is the closure in JavaScript can access variables?

In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

How does closures work in JavaScript?

A Closure is a combination of a function enclosed with references to its surrounding state (the lexical environment). In JavaScript, closures are created every time a function is created at run time. In other words, a closure is just a fancy name for a function that remembers the external things used inside it.

Is closure encapsulation in JavaScript?

The simplest and most elegant way to create encapsulation in JavaScript is using closures.


2 Answers

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.

like image 131
Jakob Avatar answered Oct 31 '22 22:10

Jakob


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

like image 44
Simon Lindholm Avatar answered Oct 31 '22 23:10

Simon Lindholm