CoderGLM CoderGLM - 2 months ago 13
Javascript Question

how to release closure's memory in javascript?

A closure:

function test() {
var count = 0;

return function() {
count++;
};
}


As we all know, the
count
won't release after
test()
be called, and now if the closure is useless to me, how could I release memory of it?

Answer

All objects in javascript is garbage collected, regardless of weather they're involved in a closure or not. In your code above, if you do:

var x = test();

then of course the memory for count cannot be released because it may be used later by x. However if you do:

var x = test();
x = "";

the memory for count will be garbage collected sooner or later.