# JavaScript 避免内存泄漏

**URL:** <https://www.isharkfly.com/t/javascript/8744>\
**Category:** 前端\
**Created:** [October 30, 2012, 4:55pm UTC](https://www.isharkfly.com/t/javascript/8744 "2012-10-30T16:55:57Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [October 30, 2012, 4:55pm UTC](https://www.isharkfly.com/t/javascript/8744/1 "2012-10-30T16:55:57Z")

</div>

幸好，JavaScript 中的内存泄漏是可以避免的。当确定了可导致循环引用的模式之后，正如我们在上述章节中所做的那样，您就可以开始着手应对这些模式了。这里，我们将以上述的 由事件处理引起的内存泄漏模式 为例来展示三种应对已知内存泄漏的方式。

打破循环引用[code]  
  
  
“Click Here”

[/code]通过添加另一个闭包来避免 JavaScript 对象和 DOM 对象间的循环引用。 

添加另一个闭包[code]  
  
  
“Click Here”

[/code]通过添加另一个函数来避免闭包本身，进而阻止了泄漏。

避免闭包自身[code]  
  
  
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>

```

[/code]
