问题描述:

Hello fellow programmers!

My whole code is based on the following structure:

function pseudoClass() {

var privateVar = 0;

return {

incrementVar: function() {privateVar += 1;},

getPrivateVar: function() {return privateVar;}

}

}

var test1 = pseudoClass();

I want to protect "privateVar" while being able to manipulate it. "pseudoClass" will be instanciated only once at a time. I believe "test" involves a closure. When I'm done with "test", I might create "test2" later to start all over again (privateVar being set to 0 again). I'm not interested in merely reseting "test" to 0.

Now, here is the question. What happens with the closure when "test" is not used anymore? Is it garbage collected or could it cause memory leaks? If not, in which similar situation would it do so? I hope my question is clear enough, I'm quite new to this stuff. Thanks!

网友答案:

There's a common misconception that closures inherently cause memory leaks. They don't - provided they become unreachable they can be garbage collected like any other object. They tend to cause problems when they are leaked, because they prevent their inherited parent scope from being garbage collected. This can give closures an extremely large retained size.

In your example, the object returned by pseudoClass and the scope its methods close over (containing privateVar) become eligible for GC when there are no other references to it:

var test1 = pseudoClass();
test1 = null;

// The object, closures and privateVar can be garbage collected

If there is another reference to the object returned by pseuedoClass or any closures that include the function's scope, the object and scope cannot be garbage collected. This pattern is a common cause of memory leaks.

var test1 = pseudoClass();
var leak = test1.incrementVar
test1 = null;

// Nothing can be garbage collected, since `incrementVar` needs to retain its parent scope
相关阅读:
Top