This is called closure. When you do this, you are setting a global variable called i. So, when you click it, your click function remembers this variable which is always 2 as it is its value at the end of the loop.
Now why is it a globa variable?, because javascript has function scop instead of block scope
<script type="text/javascript">
var imGlobal = "Hello!";
// ^ Watch out for the scope! I'm NOT inside a function
for (var i = 0; i < 2; i++){}
// ^ Watch out for the scope! I'm NOT inside a function EITHER!!!
function(){
// ^ Watch out for the scope! I'm inside a function
var imNOTGlobal = "I won't exist after the function has returned (under certain circumstances ;])";
}();
console.log(imGlobal); //"Hello!"
console.log(i); //2
console.log(imNOTGlobal); //undefined
</script>
Closure is a way of javascript to do useful things like this:
// To get the nth prime number
var getPrimeNumber = function (){
var primeNumbers = [];
return function(n){
if(!primeNumbers[n]){
// Calculate the nth prime number and insert it into the array.
}
return primeNumbers[n];
};
}(); // The function is executed immediately
// making "var getPrimeNumber" to hold the result of the execution
// which is a function that remembers primeNumbers
// and is who does the actual calculation
getPrimeNumber(1);
getPrimeNumber(2);
getPrimeNumber(3); // Calculate it the first time
getPrimeNumber(4);
getPrimeNumber(3): // This is already calculated!
// The array ends up with 4 slots;
Everytime you call the function, it will check if it has already calculated the nth prime number and store it in an array which is accessible for the closure, this way you don't have to calculate everytime the function is asked the nth number.
Now, what is useful about this?: You get to use a variable that is not initialized everytime you call getPrimeNumber();and this variable is NOT a global object.
Note: The function doesn't work, but illustrates the point.
$("li").click(function(){ alert($(this).index()) });