title: Javascript variable scoping - fixing the value of a variable in an anonymous function
body: <p>I am using an array, to construct callback functions to a plugin(select2):</p>
  
  <p>Let's say that I tell my <code>&lt;select&gt;</code> element, that when something is selected, <code>function1</code> should be fired, and after that <code>function2</code> should be fired, with the provided parameters.</p>
  
  <p>Yet, when something is unselected, <code>function3</code> should be fired.</p>
  
  <p>When I initialize my <code>&lt;select&gt;</code> element, I use the following javascript code.</p>
  
  <pre><code>events = {
     'select': Array(
           { function: 'function1' },
           { function: 'function2',
             parameters: Array(1,2)
           }
     ),
     'unselect': Array(
           { function: 'function3' }
     )
  }; //this is normally generated dynamically
  for (var event in events)
     {
      var eventGroup=events[event];
      jQuery(this).on("select2:"+event, function (e) {
          var select=jQuery(e.currentTarget);
          var subtype=e.type.split(":")[1];
          console.log("Event group is", eventGroup);
  
          for (var i=0;i&lt;eventGroup.length;i++)
              {
                  var functionParams=new Array(e);
                  if (eventGroup[i]['parameters']) for (var z=0;z&lt;eventGroup[i]['parameters'].length; z++) functionParams.push(eventGroup[i]['parameters'][z]);
                  if (eventGroup[i]['return']) return window[eventGroup[i]['function']].apply(this, functionParams);
                  else window[eventGroup[i]['function']].apply(this, functionParams);
  
              }
          });
  
      }
  </code></pre>
  
  <p>The events fire correctly, so this is not an error in the plugin, the problem is, they always fire the function of the LAST element of the PHP generated array(in this case, function3).</p>
  
  <p>So the code makes two anonymous functions for each event (<strong>select</strong> and <strong>unselect</strong>), but the <code>eventGroup</code> variable is the same in both of those anonymous function, it is always the last value what was assigned to it. I always thought that when I define an anonymous function, it stores the values of the variables that are used in it, as they were at the time of definition, but it looks like I was wrong. </p>
  
  <p>How could I attach another variable to an anonymous function, which remains always what it was at the time of definition? (how could I attach the CURRENT value of <code>eventGroup</code> to the defined anonymous function?)</p>