0

This might have been asked several times, but I don't find it. The following code does - of course - not what it obviously intends:

var arr = [];
var count = 10;

var funct = function() { console.log("count when called: ", count); };


while (count--) {

  arr.push(funct);
}


for (i in arr) {
  arr[i]();
}

I got logged -1 in each for loop, because the function accesses the count value of the environment in which it was created. and count has the -1 value after the while loop.

What I need is something like passing an argument to the creation of the function. Any hints?

1

3 Answers 3

1

Your function needs to have a parameter, and then return a function that will make use of that parameter so it can be executed later. Something like this should work:

var arr = [];
var count = 10;

var funct = function(c) { 
  return function() {console.log("count when called: ", c);} 
};


while (count--) {
  arr.push( funct(count) );
}


for (i in arr) {
  arr[i]();
}

Sign up to request clarification or add additional context in comments.

Comments

1

What you can do is to wrap the function funct within a second closure in order to create a local version of the variable count.

For example:

var arr = [];
var count = 10;

var funct = function () {
  var currentCount = count;
  return function() { console.log("count when called: ", currentCount); };
}


while (count--) {
  arr.push(funct());
}


for (i in arr) {
  arr[i]();
}

Output:

count when called:  9
count when called:  8
count when called:  7
count when called:  6
count when called:  5
count when called:  4
count when called:  3
count when called:  2
count when called:  1
count when called:  0

JSFIDDLE: https://jsfiddle.net/gwswjtug/

Open the console to see the results.

Comments

1

Use closures - http://www.w3schools.com/js/js_function_closures.asp

var arr = [];
var count = 10;

var funct = function(i) { 
    return function() {
        console.log("count when called: ", i); 
    }
}


while (count--) {
    arr.push(funct(count));
}


arr.forEach(function(fn) {
    fn();
});

Fiddle: http://jsfiddle.net/ort1t6e2/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.