from javascript.info:
function makeArmy() {
var shooters = []
for(var i=0; i<10; i++) {
var shooter = function shoot() {
alert( shoot.i )
}
shooter.i = i
shooters.push(shooter)
}
return shooters
}
var army = makeArmy()
army[0]() // 0
army[1]() // 1
The interesting part:
var shooter = function shoot() {
alert( shoot.i )
}
shooter.i = i
My question is this: why does the following not work:
var shooter = function() {
alert( shooter.i )
}
shooter.i = i
In other words, why does the first one work as expected, while the second one does not? What is the actual difference between the first (giving the function itself a name and using it from within the function), and the second one (using the variable which references to the function)?
You can't refer to the variable shooter
until its initializer expression (function() {...}
) has completed. If instead you said
var shooter;
shooter = function() { alert(shooter.i); }
it would work OK because the variable is already declared and in scope at the point where the function expression is evaluated.