You should do:
var o = {};
for(var i = 0; i < 5; i++) {
(function(i) { // <- self-executing anonymus function with a parameter i
o[i] = function () {
console.log(i); // <- i here will be the argument i,
// not the i from the loop
};
})(i); // <- pass i as an argument
}
o[3]();
What happens is that you create something called closure so as to keep the state of i.
Closure means that an inner function keeps a reference to the outer function and so gains access to its variables and parameters (even after the outer function has returned).
A trivial example for closure is:
function outer(arg) {
var variable = 5;
arg = 2;
function inner() {
alert(variable); // <- the inner function has access to the variables
alert(arg); // and parameters of the outer function
}
}
A self-executing (self-invoking, or immediate) function is a function that is called right after it is declared.
(function() {
alert("executed immediately");
})();
The combination of both and the fact that only functions have scope in Javascript, leads you to the technique mentioned above to create a scope with a new function which keeps the state of i, which would otherwise be changed by the inner function because of closure.