Closure Inspector

From FirebugWiki

Revision as of 14:24, 3 February 2013 by Florent (Talk | contribs)
Jump to: navigation, search

Closure inspector is a feature available from Firebug 1.11.2 that aims at accessing JavaScript closure variables.

Contents

Closures

This section aims at defining what are closures. If you know them, then jump to Closure Inspector.

Definition

You might know what are closures without knowing how to name them.

Wikipedia says:

In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function. A closure—unlike a plain function pointer—allows a function to access those non-local variables even when invoked outside of its immediate lexical scope.

In other words, the closures combines both the function and its referencing environment, which stores the references of the variables declared in its parent scopes. So when the function is called, it can access to variables wherever the call site is.

If the concept of closure is still vague, just go on to the below example.

Basic example

Here is a basic example of the creation of a closure:

function Person()
{
	var name = "Arthur";
 
	this.introduce = function()
	{
		console.log("Hello, my name is " + name);
	}
}
 
// create an instance of Person:
var someone = new Person();
 
// we call a closure !
someone.introduce(); // prints "Hello, my name is Arthur"

someone.introduce is a closure because this function uses a variable outside its own scope (you must have noticed there was no name variable inside the introduce method).

But where someone.introduce is called in the above example (i.e. its call site), the name variable cannot be accessed... except with specific tools like Closure Inspector.

Closure Inspector

Using the Command Line

The syntax to access the closure variables is as follow:

closure.%variable

In the above example, you would access to name using this expression:

someone.introduce.%name

Which returns: "Arthur".

Note that Closure Inspector also lets you change values too:

someone.introduce.%name = "Trillian";
someone.introduce(); // ==> "Hello, my name is Trillian"

Using the DOM Panel

In order to go through closures in the DOM panel, you need to activate the "Show Closure" option:

Activate Show Closure.png


Then you can access to closure variables by expanding the function properties and (closures), as below:

Access Closure Variables.png

Using the Watch Panel

Watch panel allows you to access to closure variables both via an expression as for the Command Line and via object browsing as for the DOM Panel (you would also need to enable the "Show Closures" option).

Personal tools