function create(){
var ret=new Array();
for(var i=0;i<10;++i){
ret[i]=function(){return i;};
}
return ret;
};
var a1=create();
console.log(a1[2]());
The code above will print "10".
I know the inside "create()", the variable "i" in for loop, has execution context of "create()", so the 10 elements of "ret" are all functions that will return "10". So inside "create()", ret2 will return 10. No problem.
But outside "create()", there's no more "i". If I try "console.log(i)" it will give exception like below:
console.log(i);
^
ReferenceError: i is not defined
Why, closure can still visit "i" as a reference, while outside blocks cannot? The life cycle of "i" is ended!