When actually is a closure created?

Posted by Jian Lin on Stack Overflow See other posts from Stack Overflow or by Jian Lin
Published on 2010-05-06T10:45:23Z Indexed on 2010/05/06 10:58 UTC
Read the original article Hit count: 429

Filed under:
|
|

Is it true that a closure is created in the following cases for foo, but not for bar?

Case 1:

<script type="text/javascript">

    function foo() { }

</script>

foo is a closure with a scope chain with only the global scope.

Case 2:

<script type="text/javascript">

    var i = 1;
    function foo() { return i; }

</script>

same as Case 1.

Case 3:

<script type="text/javascript">

    function Circle(r) {
        this.r = r;
    }
    Circle.prototype.foo = function() { return 3.1415 * this.r * this.r }

</script>

in this case, Circle.prototype.foo (which returns the circle's area) refers to a closure with only the global scope. (this closure is created).

Case 4:

<script type="text/javascript">

    function foo() { 
        function bar() { 
        }
    }

</script>

here, foo is a closure with only the global scope, but bar is not a closure (yet), because the function foo is not invoked in the code, so no closure goo is ever created. It will only exist if foo is invoked , and the closure bar will exist until foo returns, and the closure bar will then be garbage collected, since there is no reference to it at all anywhere.

So when the function doesn't exist, can't be invoked, can't be referenced, then the closure doesn't exist yet (never created yet). Only when the function can be invoked or can be referenced, then the closure is actually created?

© Stack Overflow or respective owner

Related posts about closures

Related posts about closure