简体   繁体   中英

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 !

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

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;
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM