2

for debugging memory leak issue, I am wondering if function closure will be kept in the memory just like any global variables?

function() {
    var  blah;
    return function() {
    }
}
Adam Lee
  • 24,710
  • 51
  • 156
  • 236

2 Answers2

1

If you mean the inner function, it won't. It will be discarded when there are no references to the function object.

function() A {
    var  blah = //someobject;
    return function() {
    }
}

var x = A();
//inner function and blah created
x = null;
//inner function (and the variable blah) can now be garbage collected
ralh
  • 2,514
  • 1
  • 13
  • 19
0

A closure works like a garbage collected class - that is, enclosed variables are allocated for each closure created:

function foo () {
    var x = 0;
    return function(){return x}
}

var a = foo(); // memory allocated for x
var b = foo(); // memory allocated for second instance of x

/* This is what I mean by it behaves like a class: returning the
 * inner function creates a new closure much like calling a class
 * with `new` creates a new object
 */

a = null; // memory for x will be de-allocated in the next round
          // of garbage collection

b = null; // memory for second x will be de-allocated eventually

function bar () {
    y = foo()
}

bar(); // memory for third instance of x is allocated when foo()
       // is called inside bar().

// memory for third instance of x will be de-allocated eventually
// after bar() returns because y has already been de-allocated
slebetman
  • 109,858
  • 19
  • 140
  • 171
  • Also read this long answer explaining the relation of closures and the call stack: http://stackoverflow.com/questions/26061856/javascript-cant-access-private-properties/26063201#26063201. Only keep in mind that js is a garbage collected language - a fact that isn't mention in that linked answer. – slebetman Aug 17 '15 at 14:53