title: How can I maintain scope in node.js callbacks?
body: <p>I'm an experienced software developer, but pretty new to JS and to node. I'm not a big fan of super-nested code, so I've been trying to break callbacks out into their own functions. I'm having trouble though with figuring out how to maintain scope when the callback fires. Digging around I read that if I created a closure over the callback it would work, but it doesn't seem to work the way I expected it would.</p>
  
  <p>Here's a very simple version of the kind of code that isn't working for me:</p>
  
  <pre><code>function writeBody()
  {
      res.end("&lt;h1&gt; Hooray! &lt;/h1&gt;");
  }
  
  http.createServer(function(req, res)
  {
      res.writeHead('Content-Type', 'text/html');
      setTimeout(function(){writeBody()}, 2000);
  }).listen(8000);
  </code></pre>
  
  <p>I thought that by wrapping the writeBody() call in the function() closure I would have the scope I needed after the timeout, but when writeBody() fires I get </p>
  
  <blockquote>
    <p>ReferenceError: res is not defined</p>
  </blockquote>
  
  <p>Can anyone tell me what boneheaded thing I am doing wrong?</p>