1. What is a closure and the scope chain involved in the closure will not be discussed here.
2. JavaScript garbage collection mechanism
JavaScript does not need to manually release memory, it uses an automatic garbage collection mechanism (garbage collection). When an object is useless, that is, when no variable in the program refers to the object, the variable will be released from memory.
3. Circular reference
Three objects A, B, C
AàBàC: A certain attribute of A refers to B, and C is also referenced by an attribute of B. If A is cleared, then B and C are also released.
AàBàCàB: Here a certain attribute of C is added to reference the B object. If this is to clear A, then B and C will not be released because a circular reference is generated between B and C.
Therefore, closures are very easy to create circular references. Fortunately, JavaScript can handle such circular references very well.
There are several types of memory leaks in IE, and there are detailed explanations here (
http://msdn.microsoft.com/en-us/library/bb250448.aspx).
Only one of them is discussed here, namely the memory leak caused by circular reference, because this is the most common situation.When there is a circular reference between a DOM element or an ActiveX object and a normal JavaScript object, IE has special difficulties in releasing such variables. It is best to manually cut off the circular reference. This bug has been fixed in IE 7 (
http://www.quirksmode.org/blog/archives/2006/04/ie_7_and_javasc.html).
“IE 6 suffered from memory leaks when a circular reference between several objects, among which at least one DOM node, was created. This problem has been solved in IE 7. ”If in the above example (point 4) obj refers not to a JavaScript Function object (inner), but to an ActiveX object or Dom element, the circular reference formed in IE cannot be released.
Elem refers to its click event listening function, which also refers back to the elem element through its scope chain. In this way, these circular references will not be released even if you leave the current page in IE.
6. Solution
The basic method is to manually clear this circular reference. Here is a very simple example. In actual application, you can build an addEvent() function yourself and clear all event bindings on the unload event of the window.
Other methods (by: Douglas Crockford)