I am trying to understand how I can prevent memory leaks when using closures in JavaScript. Can someone let me know if what I am doing is correct?
I have a dummy function:
var testFunction = function(obj1){
//other code..
on(control, "click", function(){
obj1.label= "test";
});
};
1) does the above cause a memory leak because obj1 is being referenced in the click event.?
2) can I fix it by doing the following:
var testFunction = function(obj1){
//other code.....
on(control, "click", function(){
var newObj1 = obj1;
newObj1.label= "test";
newObj1 = null;
});
};
If this is a poor example, can someone show me better example of a closure with memory leak and how to fix it?
Thanks in advance!
I am trying to understand how I can prevent memory leaks when using closures in JavaScript.
You hardly never need to. The engine's garbage collector does that for you. It's pretty powerful, and rarely needs help.
does the above cause a memory leak because obj1 is being referenced in the click event.?
It does prevent obj1 from being garbage-collected, yes, because you still reference it. However, this does not qualify as a "memory leak", because it is intentional. You want to preserve the object in memory.
It might become a leak if testFunction is called more frequently than you expected, and if on does preserve the closure longer than needed.
can I fix it by doing the following
a) there's nothing to fix b) no, introducing an extra variable does not alter the behaviour. obj1 is still referenced from the closure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With