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() {
}
}
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() {
}
}
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
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