Recursive closure in JavaScript
A closure
is a special kind of object that combines two things: a function, and the environment in which that function was created.
No need to be confused, the behavior is same as expected to this code. Here what happening is that when you do
console.dir( a );
in your code it returns theSecond
function, i think it is clear for you.Now when you will expand this function it will show you in
Closure
the parent function (environment function
) ofSecond
, which isbuildList
. In you code it is doing the same thing.Now next thing is to expand this
function
buildList
, what it will show you is the child objects of it, Which arevar i = 0;
and thefunction first
. Your console is showing as expected.Now again when you open
first()
it will show you inClosure
the parent function(environment function
) offirst
, which isbuildList
. (same it did in step 2).
Now it repeats the step 3 again and then step 4. and so onnn... May be you understand what is happening here.