DOM: why is this a memory leak?
circular-reference, garbage-collection, internet-explorer, javascript, memory-leaks
Solution
There are two concepts that will help you understand this example.
1) Closures
The definition of a closure is that Every inner function enjoys access to its parent's function variables and parameters.
When the `addHandler()` function finishes, the anonymous function still has access to the parent's variable `el`.
2) Functions = memory
Every time you define a `function` a new object is created. What makes this example slightly confusing is that onclick is an event that can only be set to a DOM element once.
So surely `el.onclick = function(){};` will just overwrite the old function right?
Wrong! every time addHandler runs, a new function object is created.
In conclusion:
Each time the function runs it will create a new object, with a closure containing `el`. Seeing as the anonymous function maintains access to `el`, the garbage collector cannot remove it from memory.
The anon function will maintain access to el, and el has access to the function, that is a circular reference, which causes a memory leak in IE.
Problem
Consider this quote from the Mozilla Docs on JavaScript memory leaks: ``` function addHandler() { var el = document.getElementById('el'); el.onclick = function() { this.style.backgroundColor = 'red'; } } ``` The above code sets up the element to turn red when it is clicked. It also creates a memory leak. Why? Because the reference to el is inadvertently caught in the closure created for the anonymous inner function. This creates a circular reference between a JavaScript object (the function) and a native object (el). Please explain the above reasons of leakage in a simple and concise way, I'm not getting the exact point. Does the site/page face a security problem because of the leakage? How do I avoid them? What other code can cause memory leaks? How can I tell when a memory leak has occurred? I'm an absolute beginner to the topic of memory leaks. Could someone clarify this stuff for me, step by step?Also can someone help me clarify this statement "This creates a circular reference between a JavaScript object (the function) and a native object (el)."