Reputation: 15044
I have a set of arrays which i am calling inside my closures, which are declared in another file called utils.
utils.js
var array1 = [];
var array2 = [];
var array3 = [];
var array4 = [];
My Closures.js
(function() {
myObject.createWindow= function() {
someField.value = array1;
})();
Upvotes: 0
Views: 114
Reputation: 1223
Allocated memory is garbage collected when there are no ways for it to be accessed anymore. So, if an array is referenced in a closure that can still be called, it won't be garbage collected.
For example:
f = function() {
var arr1 = [];
var arr2 = [];
return function() {
return arr1;
}
};
v = f();
arr2 can be immediately garbage collected, but arr1 can't until the value of v is changed to something else because arr1 can still be accessed.
So, in your case, you have
var arr1 = [];
var arr2 = [];
...
f = function() {
return arr1;
}
so arr2 can be garbage collected (assuming it's gone out of scope and isn't referred to anywhere else), but arr1 can't be until there are no more references to it. Specifically, in your case, createWindow refers to array1, so that definitely can't be garbage collected.
But as pointed out in another post, if they both have global scope, then neither will be, because they can still be referred to anywhere.
Upvotes: 2
Reputation: 82297
Memory is considered to be leaked when it is not released when it should be. Attaching arrays to the global namespace means they will be released when the global namespace is. In other words, for them to leak, it would be because of a browser failure. They will pretty much never be collected until the page loses scope. There is nothing that can affect them after the page loses scope that you can introduce in code.
If you want your arrays to be garbage collected, then put them in a scope which will lose scope at some point. When the scope loses its scope, then the arrays will be eligible for garbage collection (but not immediately garbage collected).
Upvotes: 2
Reputation: 2778
It would be profoundly surprising if file->object resolution and garbage collection (the way javascript manages memory in general) were at all related to one another. It should not cause a memory leak.
Upvotes: -2
Reputation: 382274
If your array is at the root of your file, it's a global variable.
It will take memory, sure, but there is no specific reason for this memory to grow.
So there is no specific risk of memory leak here.
Upvotes: 4