Does javascript close new reserved space in memory for each iteration?

Im has 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); }; } ; 

I recently read a lot about closing.

There is one thing that I do not understand.

  • When i == 0, it comes to aaa with i = 0 and is executed, returning a new function that should block the value 0 .

its fine (I understand it so far).

But what happens in i == 1?

  • It returns to SAME aaa again, and now it must block the value 1 . OK

But wait! it already saves a β€œclose” for the value β€œ0”!

Does this structure (closure) create new memory space for each iteration?

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

+4
source share
3 answers

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

+4
source

Each time you call aaa , it creates a new function with a completely different context / scope, even if you use the same arguments. The closure uses memory space to store context values.

+2
source

Another word that I want to add to this and similar questions: in each call to an external function ( aaa in this case), another local variable num is created that contains the value passed from i . These are different versions of the num variable, which are remembered by each instance of the internal function (in this case, an anonymous function) created in each aaa(i) call.

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

0
source

Source: https://habr.com/ru/post/1385736/


All Articles