Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Basically that not how closures work, functions inherit their outer scopes that's how it works.</p> <pre><code>// this function only inherits the global scope function writeBody() { res.end("&lt;h1&gt; Hooray! &lt;/h1&gt;"); } http.createServer(function(req, res) // a new local varaible res is created here for each callback { res.writeHead('Content-Type', 'text/html'); // annonymous function inheris both the global scope // as well as the scope of the server callback setTimeout(function(){ // the local variable res is available here too writeBody() }, 2000); }).listen(8000); </code></pre> <p>To make it work just pass the <code>res</code> object into the function, as it's available in the timeout callback.</p> <pre><code>function writeBody(res) { // NOT the same variable res, but it holds the same value res.end("&lt;h1&gt; Hooray! &lt;/h1&gt;"); } http.createServer(function(req, res) { res.writeHead('Content-Type', 'text/html'); setTimeout(function(){ writeBody(res); // just pass res }, 2000); }).listen(8000); </code></pre> <p>But you need to watch out for things like this: </p> <pre><code>for(var i = 0; i &lt; 10; i++) { // only one i gets created here!() setTimeout(function() { console.log(i); // this always references the same variable i }, 1000); } </code></pre> <p>This will print <code>10</code> ten times, because the reference is the same and <code>i</code> gets incremented all the way up to <code>10</code>. If you want to have the different numbers you need to create a new variable for each one, either by wrapping the <code>setTimeout</code> into an anonymous self function which you pass in the <code>i</code> as a parameter, or by calling some other method which sets up the timouet and receives the <code>i</code> as a parameter.</p> <pre><code>// anoynmous function version for(var i = 0; i &lt; 10; i++) { (function(e){ // creates a new variable e for each call setTimeout(function() { console.log(e); }, 1000); })(i); // pass in the value of i } // function call version for(var i = 0; i &lt; 10; i++) { createTimeoutFunction(i); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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