first of all you should know whenever you want to run this function:
Function("console.log(i);");
this would use the current context's i
variable as its value. so you might want to do:
var functions = [];
(function foo() {
for (var i = 0; i < 5; i++) {
var f = function func() {
console.log(func._i);
};
f._i = i;
functions.push(f);
}
for (var i = 0; i < 5; i++) {
f = new Function("console.log(" + i + ");");
functions.push(f);
}
})();
for (var i = 0; i < 10; i++) {
functions[i]();
}
I changed it this way and my result is:
0, 1, 2, 3, 4, 5, 6, 7 ,8, 9
Why is that?
1- all of the functions in your first for loop use a single variable i
, and as its last value is 5 then all would print 5.
2- the other ones which get created in your second for loop, whenever they get invoked they would use the i
variable in their current context, and as far as they get invoked in your last for loop, they use the i
variable in the loop, to make it clear. you can easily change your last for loop like this:
for (var j = 0; j < 10; j++) {
functions[j]();
}
and as there is no i
variable in the context (I changed it to j
), then your output would be:
5 5 5 5 5 undefined undefined undefined undefined undefined
undefined
is there because function can not fin any i
variable in the context.