I tried to have better understanding of JavaScript. Here is a piece of code that I read from JavaScript function closures.
var funcs = [];
// create a bunch of functions
for (var i = 0; i < 3; i++) {
funcs.push(function() {
console.log(i);
})
}
// call them
for (var j = 0; j < 3; j++) {
funcs[j]();
}
The array funcs has a push callback function. I don't why in the J loop, funcs[j]() will call this function to print the i in the console.
I have tried to understand this sequencey by adding some console messages:
var funcs = [];
console.log("start");
for (var i = 0; i < 3; i++) {
console.log("i:" + i);
funcs.push(function(){
console.log(i);
})
}
console.log("J loop");
for (var j=0; j<3; j++) {
console.log("j:" + j);
funcs[j]();
}
As expected, there is 3 for all three functions.
My question is: How does funcs[j]() calls the funcs.push(...) function?
I understant the funcs[j] is reference the j element of the funcs array. But why having parentheses () will call the push(...) function?
.push()function; it calls the function that was passed to.push(), the little function withconsole.log(i);inside..push()? It is a syntax or something else?imay surprise you: stackoverflow.com/questions/750486/…