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 which has function first which also has a closure of itself ie it has repetitive loop of its own function in closure, Does anyone knows whats happening here, I am very much confused, Why there is infinte closure loop
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.