Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A <em>closure</em> is much like an object. It gets instantiated whenever you call a function. </p> <p>The scope of a <em>closure</em> in JavaScript is lexical, which means that everything that is contained within the function the <em>closure</em> belongs to, has access to any variable that is in it.</p> <p>A variable is contained in the <em>closure</em> if you</p> <ol> <li>assign it with <code>var foo=1;</code> or</li> <li>just write <code>var foo;</code></li> </ol> <p>If an inner function (a function contained inside another function) accesses such a variable without defining it in its own scope with var, it modifies the content of the variable in the outer <em>closure</em>.</p> <p>A <em>closure</em> outlives the runtime of the function that spawned it. If other functions make it out of the <em>closure/scope</em> in which they are defined (for instance as return values), those will continue to reference that <em>closure</em>.</p> <h2>Example</h2> <pre><code> function example(closure) { // define somevariable to live in the closure of example var somevariable = 'unchanged'; return { change_to: function(value) { somevariable = value; }, log: function(value) { console.log('somevariable of closure %s is: %s', closure, somevariable); } } } closure_one = example('one'); closure_two = example('two'); closure_one.log(); closure_two.log(); closure_one.change_to('some new value'); closure_one.log(); closure_two.log(); </code></pre> <h2>Output</h2> <pre><code>somevariable of closure one is: unchanged somevariable of closure two is: unchanged somevariable of closure one is: some new value somevariable of closure two is: unchanged </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload