views:

40

answers:

2

I have an associative array of objects that I want to extend with a number of functions. myCtrls //Array of objects

I do this with the following loop

$(document).ready(function() {
    for (ctrlName in fieldCtrls){
        var ctrl = fieldCtrls[ctrlName];

        ctrl.Initialize = function(){
            //Do some stuff
            ctrl.someProperty = "newValue";
        }
        ctrl.Validate= function(){
            //Do some more stuff
            ctrl.someProperty = "validation ok";
        }
}

Later on, I execute a function like this. However the variable 'ctrl' now always points to the last object in 'fieldCtrls'. How can I make the variable 'ctrl' work inside 'initialize()' and 'Validate()'?

fieldCtrls['id'].Validate();
+3  A: 

The scope would change to the calling object - fieldCtrls['id']. You should therefore be able to use this to access internal properties.

ctrl.Validate= function(){
  //Do some more stuff
  this.someProperty = "validation ok";
}
Ivar Bonsaksen
Ah, why didnt I thick of that! ;)
David
+1  A: 

This blog post describes the problem you're seeing. The var ctrl declaration is actually interpreted as being function-local, not local to the loop.

You can work around this by writing something like this instead:

$(document).ready(function() {
    for (ctrlName in fieldCtrls){
        function(ctrl) { // create a new anonymous function ...
            ctrl.Initialize = function(){
                //Do some stuff
                ctrl.someProperty = "newValue";
            }
            ctrl.Validate= function(){
                //Do some more stuff
                ctrl.someProperty = "validation ok";
            }
        }(fieldCtrls[ctrlName]); // ... and call the function right away
    }
}

This forces a new scope for ctrl for each loop iteration, so each function captures a different variable, instead of the same one each time.

(N.B. Untested, and I'm not a JavaScript guru. This problem, however, plagues most scripting languages with closure support.)

Thomas
Thank you! You managed to explain closures to me! Ive read alot about it but hadnt still grasped it.
David
Wow, and I didn't even really try. I figured I'd just post this, even though Ivar's solution is better in this particular case, but this is more generally applicable.
Thomas