幸好,JavaScript 中的内存泄漏是可以避免的。当确定了可导致循环引用的模式之后,正如我们在上述章节中所做的那样,您就可以开始着手应对这些模式了。这里,我们将以上述的 由事件处理引起的内存泄漏模式 为例来展示三种应对已知内存泄漏的方式。
打破循环引用[code]
“Click Here”
添加另一个闭包[code]
“Click Here”
避免闭包自身[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]