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 !
It’s because your
blainside 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
fiddle