I read this article, but I have some issues understanding it.
var funcs = [];
for (var i = 0; i < 3; i++) {
(function IIFE(arg) {
funcs[arg] = function output() {
console.log("My value: " + arg);
};
})(i);
}
for (var j = 0; j < 3; j++) {
funcs[j]();
}
How can I explain the mechanism of this snippet?
Start: i
has value of 0
. IIFE gets the value of i
and stores it in arg
.
funcs[0]
just get assigned to a function named output
.
second time, when i
is 1, funcs[1] gets a totally new function? Is this false?
.....
The problem is here, How does funcs[0]();
know that arg
was 0? How things interact?
Function output()
looks up and ask IIFE function
to give the required value? right? Can someone say which illustration is correct?
By Providing this picture, for example, number 1, I mean, when funcs[0]()
gets executed, output looks for arg
, it doesn't find it, then goes to higher scope and finds it. each function has it's own IIFE, for example. I'n not sure how far are this from Javascript or even programming world, but help me get it!