4

Im having this closure Code :

    for (var i = 0, link; i < 5; i++)
    {
        link = document.createElement("a");

        link.onclick = aaa(i);
        document.body.appendChild(link);
    }

    function aaa(num)
            {
                return function ()
                {
                    alert(num);
                };
            } ;

Ive been reading a lot about closure lately.

There is ONE thing which I dont understand.

  • When i==0 , it comes to aaa with i=0 and being executed which return new function which should lock the value 0.

its fine.( I understand this so far).

But what happens the i==1 ?

  • It comes again to the SAME aaa and now it should lock the 1 value. ok

But Wait ! it already saves the "closure" for the "0" value !

Does this structure(closure) is creating a new space in memory for each iteration ?

and if so - how can it be ? we have only one centralized aaa func !

1
  • Basically, the same goes for link - you're creating multiple elements of which the create code is only apparent once in the source. Commented Dec 11, 2011 at 11:49

3 Answers 3

4

Your aaa function is like a function factory; each call returns a new function (not the same) which has its num variable in its execution context set to the initial argument to aaa.

Sign up to request clarification or add additional context in comments.

Comments

2

Each time you call aaa it creates a new function with totally different context/scope, even you use the same arguments. The closure does use a space of memory to keep the context values.

Comments

0

One more word I want to add to this and similar questions: in each call of the outer function (aaa in this case), there is a different local variable num created, which holds the value passed from i. It's the different versions of the variable num that get remember by each inner function instance (the anonymous function in this case), created in each aaa(i) call.

If the parameter from function call of the outer function (aaa(i) in this case) is not passing by value but passing by reference, then different versions of the local num may point to the same object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.