Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>CLOSURES</strong></p> <p><a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" rel="noreferrer">Closures</a> are a little mind-blowing at first. They are a feature of javaScript and several other modern computing languages.</p> <p>A closure is formed by an executed instance of a function that has an inner function (typically an anonymous event handler or named method) that needs access to one or more outer variables (ie. variables that are within the outer function but outside the inner function). The mind-blowing thing is that the inner function retains access to the outer variables even though the outer function has completed and returned at the time that the inner function executes!</p> <p>Moreover, variables trapped by a closure are accessible <em>only</em> to inner functions and not to the further-out environment that brought the closure into being. This feature allows us, for example, to create class-like structures with private as well as public members even in the absence of language keywords "Public" and "Private".</p> <p>Closures are made possible by inner functions' use of outer variables suppressing javaScript's "garbage collection" which would otherwise destroy the outer function's environment at some indeterminate point after completion.</p> <p>The importance of closures to good, tidy javaScript programming cannot be overstressed. </p> <p>In the code below the function <code>getData()</code> forms, at each call, a closure trapping <code>id1</code> and <code>id2</code> (and <code>url</code>), which remain available to the anonymous ajax response handler ($.get's third argument). </p> <pre><code>$(document).ready(function() { function getData(url, id1, id2) { $.get(url, Common.genSafeId(), function(data) { $(id1).html(data); $(id2).addClass("empty"); }); } getData('/activity', '#stream', '#load_activity'); getData('/messages', '#message', '#load_messages'); getData('/deals', '#new_deals_container', '#load_deal'); getData('/tasks', '#task_frames', '#load_task'); }); </code></pre> <p>Thus, rather than writing four separate handlers, we exploit the language's ability to form closures and call the <em>same</em> function, <code>getData()</code>, four times. At each call, <code>getData()</code> forms a new closure which allows $.get's response handler (which is called asynchronously when the server responds) to address <em>its</em> DOM elements.</p>
 

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