Closures

Definition

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:

functionPerson(){varname="Arthur";this.introduce=function(){console.log("Hello, my name is "+name);}}// create an instance of Person:varsomeone=newPerson();// 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.

Using the DOM Panel

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

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

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