1. 循環引用javascript
<html> <body> <script type="text/javascript"> document.write("Circular references between JavaScript and DOM!"); var obj; window.onload = function(){ obj=document.getElementById("DivElement"); document.getElementById("DivElement").expandoProperty=obj; obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX")); }; </script> <div id="DivElement">Div Element</div> </body> </html>
2. 調用外部函數html
<html> <head> <script type="text/javascript"> document.write("Circular references between JavaScript and DOM!"); function myFunction(element) { this.elementReference = element; // This code forms a circular reference here //by DOM-->JS-->DOM element.expandoProperty = this; } function Leak() { //This code will leak new myFunction(document.getElementById("myDiv")); } </script> </head> <body onload="Leak()"> <div id="myDiv"></div> </body> </html>
3. 閉包java
function parentFunction(paramA) { var a = paramA; function childFunction(){ return a + 2; } return childFunction(); }
1. 破解循環引用閉包
<html> <body> <script type="text/javascript"> document.write("Avoiding memory leak via closure by breaking the circular reference"); window.onload=function outerFunction(){ var obj = document.getElementById("element"); obj.onclick=function innerFunction() { alert("Hi! I have avoided the leak"); // Some logic here }; obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX")); obj = null; //This breaks the circular reference }; </script> <button id="element">"Click Here"</button> </body> </html>
2. 添加另外一個閉包ide
<html> <body> <script type="text/javascript"> document.write("Avoiding a memory leak by adding another closure"); window.onload=function outerFunction(){ var anotherObj = function innerFunction() { // Some logic here alert("Hi! I have avoided the leak"); }; (function anotherInnerFunction(){ var obj = document.getElementById("element"); obj.onclick=anotherObj })(); }; </script> <button id="element">"Click Here"</button> </body> </html>
3. 避免閉包函數
<html> <head> <script type="text/javascript"> document.write("Avoid leaks by avoiding closures!"); window.onload=function() { var obj = document.getElementById("element"); obj.onclick = doesNotLeak; } function doesNotLeak() { //Your Logic here alert("Hi! I have avoided the leak"); } </script> </head> <body> <button id="element">"Click Here"</button> </body> </html>