0

Is there a way to create a variable that is specific to a function instance but is unique among all the objects created. The best way to explain is through an example.

Let's say I have a loop which iterates through a number of objects. Within that loop I create a new object and assign an annonymous function to a property of the object. The function is tied to a callback handler in the object I created. Within that callback function I want to assign a unique index so that I can access a global array object.

var index=0;
var bar = new Array;
while(true)
{
   foo = getObject(); //this is a factory method
   foo.eventhandler = function()
                         {
                             var internalIndex = index;
                             bar[internalIndex].readline;
                             //do some things with internal index when called
                          }
   bar[index]=foo;
   index++;
}

The reason this is required is that I have to wait for a number of responses to happen which will fire the eventhandler when completed. Once these are complete I need to work with the data that will be contained within the specific foo object. The event handler tells me nothing about the parent object. I am working with the PhantomJS framework and the event handler is this particular method http://phantomjs.org/api/webpage/handler/on-load-finished.html

Any insight or ideas would be deeply appreciated.

Count Zero
  • 237
  • 2
  • 13
  • exact duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Bergi Feb 18 '14 at 20:15
  • Thanks very much Bergi...I really struggled with this. I just had an ah ha moment with closures after thinking I understood them – Count Zero Feb 18 '14 at 20:54

0 Answers0