title: Efficiency with JavaScript Callbacks
body: <p>I just wanted to confirm a suspicion of mine.</p>
  
  <p>I stumbled across an article which recommended using Socket.io in the following fashion:</p>
  
  <pre><code>var app = require('express').createServer()
  var io = require('socket.io').listen(app);
  
  app.listen(8080);
  
  // Some unrelated stuff
  
  io.sockets.on('connection', function (socket) {
      socket.on('action1', function (data) {
          // logic for action1
      });
  
      socket.on('action2', function (data) {
          // logic for action2
      });
  
      socket.on('disconnect', function(){
          // logic for disconnect
      });
  });
  </code></pre>
  
  <p>I feel like the following would be a better use of resources:</p>
  
  <pre><code>var app = require('express').createServer()
  var io = require('socket.io').listen(app);
  
  app.listen(8080);
  
  // Some unrelated stuff
  
  io.sockets.on('connection', function (socket) {
      socket.on('action1', action1);
      socket.on('action2', action2);
      socket.on('disconnect', disconnect);
  });
  
  function action1(data) {
      // logic for action1
  }
  
  function action2(data) {
      // logic for action2
  }
  
  function disconnect() {
      // logic for disconnect
  }
  </code></pre>
  
  <p>My feeling is that although the anonymous function that handles the <code>connection</code> event is only created in memory once, the anonymous functions that handle <code>action1</code>, <code>action2</code>, and <code>disconnect</code> are created in memory for every socket connection. The issue with the second approach is that <code>socket</code> is no longer in scope.</p>
  
  <p>So firstly, is my suspicion about the creation of functions true? And secondly, if so is there a way to get <code>socket</code> in scope for the named functions?</p>