Reputation: 675
let's say I have a 'magical' function like so... (magical will be explained)
var arr = ['hello','I','am','in','an','array'];
(function() {
var z = document.getElementById('z');
//before edit: a = arr;
//let's leak memory... for fun!
z.onclick = function () {
var something = ...; //something, the uglier the better :P
//before edit: a.push(something);
arr.push(something);
something = null;
};
//now lets say by doing so I 'magically' fix my memory leak
//before edit: a = z = null;
z = null;
}());
But what if I was to do this instead...
//instead of a = z = null;
return null;
By retuning null to my self invoking function would that mark all local variables (a, z) for garbage collection or would they still have reference within the browser and thus still take up memory?
Note: I'm trying to take into consideration legacy browsers like ie7 amongst others. Also, I'm 'trying' to teach myself JavaScript so this might not make too much sense.
Upvotes: 3
Views: 197
Reputation: 7452
Because you have bound the closure function to onclick. The memory associated with 'var a' be maintained till you release the onclick handler.
- Even if you don't set 'var a' to null, memory associate with 'var a' should be insignificant as 'var a' only has reference to a global object 'arr'.
- Setting 'var z' to null has no effect.
- If you could avoid using 'var a' in your closure then 'var a' will be freed up.
- When click happens, function will get runtime error, as 'var a' is null.
- Returning null from the function has no significance in memory usage.
Upvotes: 4