开发者

closures terminology and semantic doubt

If I have the following code:

function foo() 
{
    var a = [];
    for(var i = 0; i < 3; i++)
    {
        a[i] = function(x)
        {
            return function()
            {
         开发者_如何学Python       return x;
            }
        }(i);
    }
    return a;
}

the closure is created when I call (i) at every iteration or when I define the inner functions?

and then a lambda expression is a closure?

Thanks.


The closure is created by virtue of the fact that you're returning a function that has access to the local variable x, which was defined as the only member of the formal parameters list.

So the functions stored at a[i] have closed around their unique x which was in the same scope, and as such, have access to it. Because this variable is accessible only by this function that was passed out of the self invoking function, you have a closure.

I'd note that it would be better if you did not use a self invoking anonymous function here since it is unnecessary and adds overhead. Instead declare a named function, and call that.

function foo() 
{
    var a = [];
    function retain_i(x)
    {
        return function()
        {
            return x;
        }
    }
    for(var i = 0; i < 3; i++)
    {
        a[i] = retain_i(i);
    }
    return a;
}

EDIT: To be more specific to your question:

the closure is created when I call (i) at every iteration...

No, this doesn't create a closure. The closure is created when you return the function that has closed around the x parameter, which would be otherwise inaccessible outside the self-invoking function.

If you didn't return that function, you wouldn't have a closure.

So as you can see from the modified code example I gave, the definition/declaration of a function doesn't create a closure. Rather the execution of a function that passes out of it some other function that has access to otherwise inaccessible variables creates a closure.


the closure is created when your define the function, not when you run it -- this is called lexical scoping.


Closures are created on function definitions.

Therefore in your example they are created twice for each iteration - first time when the outer function is declared, and a second time when it is invoke, defining an inner function.

The result assigned to the cell i of the array are functions returning i.

The other poster is correct in calling it "lexical" scoping - most modern languages seem to use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜