0
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!

Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • 1
    In short, the `i` is scoped inside the `create()`. The outside of the function has neved had access to it. – tedcurrent Aug 19 '16 at 07:04
  • This is precisely the defining characteristic of a *closure*. – deceze Aug 19 '16 at 07:07
  • JavaScript has two scopes: global and local. A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout your program. A variable that is declared inside a function definition is local. It is created and destroyed every time the function is executed, and it cannot be accessed by any code outside the function. JavaScript does not support block scope (in which a set of braces {. . .} defines a new scope), except in the special case of block-scoped variables. https://msdn.microsoft.com/en-us/library/bzt2dkta(v=vs.94).aspx – Sal Al Aug 19 '16 at 07:21

0 Answers0