rbag
rbag

Reputation: 137

function array and strange behaviour

I have the following code:

var arr = [{Name: "foo", action: function(){ alert("foo")}},
       {Name: "bar", action: function(){ alert("bar")}}
      ]

var arr2 = {};

for(var i =0; i< arr.length; i++)
{
    var bla = arr[i];
    arr2[bla.Name] = function(){ bla.action() };
}          

arr2.foo();
arr2.bar();

that alerts two times "bar". when instead I do

    arr2[bla.Name] = bla.action;

that works.

any way to make it works in the first case (I need to append other things in my function)

Thanks !

Upvotes: 2

Views: 66

Answers (2)

mpen
mpen

Reputation: 282825

It's because your bla inside your anonymous function is a reference and it keeps being updated inside the loop to point to the next object. When the loop terminates they will all point to the last element you referenced inside your loop.

You can fix it by doing something like

arr2[bla.Name] = (function(x) { return function(){ x.action(); }})(bla);

fiddle

Upvotes: 3

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

The value of bla is changing and the function you create will always use the value as it is when it is called.

You might create a closure to protect the bla variable :

for(var i =0; i< arr.length; i++) {
    (function(bla){
        arr2[bla.Name] = function(){ bla.action() };
    })(arr[i]);
}     

If your action functions don't need any context or arguments, you might also simplify the loop in

for(var i =0; i< arr.length; i++) {
    var bla = arr[i];
    arr2[bla.Name] = bla.action;
}    

Upvotes: 2

Related Questions