1

I am building an array of functions that will be called at a latter time that looks like:

callbackArray = [];

for(var i = 0; i < 5; i ++) {
  callbackArray.push(function() {
    console.log(i);
  });
}

for(var i = 0; i < callbackArray.length; i ++) {
  // This will not preserve the value of i
  callbackArray[i]();
}

This will print 4,4,4,4,4. But I need a way to preserve the value of i, so that it doesn't keep the same reference, but creates a new local copy of values. The expected results should be 0,1,2,3,4. This is a simplified example to show the problem. However the variable i, should be anything like objects, arrays, functions, or primitives.

How can I do this?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Dr.Knowitall
  • 10,080
  • 23
  • 82
  • 133

1 Answers1

1

This might help

var callbackArray = [];

// create a function that returns a new function with "i" properly scoped
var fn = function (i) {
    return function () {
        console.log(i);
    };
};

for(var i = 0; i < 5; i ++) {
    callbackArray.push(fn(i));
}

callbackArray[1](); // output 1
callbackArray[4](); // output 4
callbackArray[0](); // output 0

You can also use $.proxy if you are using jquery to achieve the same effect

See api docs for proxy

user1318677
  • 116
  • 4
  • 1
    Why do you think the OP uses jQuery when the function is tagged `node.js`? – Felix Kling May 24 '14 at 21:25
  • riiight. sorry about that. I guess you can check the jquery git hub repo and see how the proxy function works. @see https://github.com/jquery/jquery/blob/master/src/core.js – user1318677 May 25 '14 at 19:14