JavaScript closure and scope chain -


Can anyone explain why document.write part always 10 output?

  function creatFunctions () {var results = new array (); For (var i = 0; i & lt; 10; i ++) {result [i] = function () {return i; }} Return result; } Var funcs = creatFunctions (); For (var i = 0; i & lt; funcs.length; i ++) {document.write (funcs [i] () + "

I think the answer to this question is more intense than the duplicate question , so this post is worth keeping.

"post-text" itemprop = "text">

Sure.

In your in the loop, you reference i . Do you expect this to happen that every stop time ceremony has been created but I get a snapshot, so in the first ceremony it will return 0, then 1, etc.

What is actually happening is that external variables each closure i is to get references, which i to i in the loop as .

So, for the first time through the loop, you get a task that gives i , which is 0 at this point. Next time you get two functions which are i , which is now 1, etc.

In the loop at the end, i == 10 , and each function i , so they all return 10

Update address address question.

It's a little confusing since you use i in two different contexts. I could make a very slight changes in your code will, so that it becomes clear that what is happening:

  function creatFunctions () {var result = new Array (); For (var i = 0; i & lt; 10; i ++) {result [i] = function () {return i; }} Return result; } Var funcs = creatFunctions (); // Note: I it`s the `unrelated_variable` for I`d change (unrelated_variable = 0 var; unrelated_variable & LT; funcs.length; unrelated_variable ++) {document.write (funcs [unrelated_variable] () + '& lt ;);}   

... You can return all the functions in your creatFunctions () function i < / code>. in particular, they say that you return I to create the loop.

other variables, which I unrelated_variable has been named, there is no effect on the price derived from your closing.

  Results [i] = F Quote () {return i;}   

... is not similar to the result [2] = 2 . This means the result [2] = the_current_value_of_i

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -