Javascript内存泄露以及如何避免内存泄露

Javascript内存泄露的状况

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();
}

如何解决Javascript内存泄露

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>