Reclosing in Javascript

enter image description here

function buildList( list ) { var i = 0; var first = function () { console.log( "in" ) console.log( i ); } var Second = function () { console.log( "out" ) first(); } return Second; } var a = buildList( [1, 2, 3] ) console.dir( a ); a(); // Here closure is created which has function first ,Here first also has one closure of itself that means recursive closure 

When I see my console in Chrome, it has a closure in which there is a function that first has a closure function, i.e. it has a repeating cycle of its own function in closure. Does anyone know what is going on here, I'm very confused, Why is there a closed loop of closure

+6
source share
2 answers

A closure is a special kind of object that combines two things: a function and the environment in which this function was created.

  • Not to be confused, the behavior is the same as expected in this code. It happens here that when you do console.dir( a ); in his code, it returns a Second function, I think it is clear to you.

  • Now, when you expand this function, it will show you in closure parent function ( environment function ) Second , which is equal to buildList . In code, you do the same.

  • Now you need to expand this function buildList , what it will show you are its child objects, which are var i = 0; and function first . Your console appears as expected.

  • Now, when you open first() , it will show you in closure parent function ( environment function ) first , which is equal to buildList . (same as in step 2).

Now he repeats step 3 again, and then step 4. and so on ... Maybe you understand what is happening here.

+2
source

Developer tools display a variable a, which is a variable that points to an anonymous function / close.

In javascript, a function is defined in scope and can also determine a scope by its body block. A region “knows” all the variables inside the defining block and all variables defined outside the function, but in the hierarchy of regions in which the scope is defined.

Tools display the volume of the returned function ( a in this case). The function first defined in the framework of the function a .

The variable first also known in the realm of the anonymous function assigned to the variable first .

And this is what you get on the screen: first is a variable containing a function. Within this function, the variable first known, which points to the function. As part of this function ...

You see?

0
source

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


All Articles