<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(1000).join("XXXXX"))
obj = null //This breaks the circular reference
}
</script>
<button id="element">Click Me</button>
</body>
</html>
在 https://www.ibm.com/developer... 这篇IBM 关于JS内存泄漏的文章中,提到 DOM 与 JS 对象 obj 存在循环引用。为什么这两者存在相互引用呢?另外,文中也提到解决方法:obj = null
打破循环引用。为什么我在 Chrome 的 Profile 中,无论 obj = null
是否存在这句,内存占用量是相等的,是否说明这句无效,依然存在内存泄漏呢?
DOM与obj 循环引用 楼主你先要明白 id为element的这个元素和obj的关系 如果没有定义obj这个变量 那这个dom节点就不存在了吗?
obj=null
只是把obj
这个对节点的引用去掉了 这个元素本身还是存在的啊 所以内存当然没有变化楼主你调用一下
obj.remove()
把节点从dom树里删除 就看出区别了 不过可能数据量太小不明显