javascript - 该模式如何获得循环引用

标签 javascript memory-leaks

全部:

我对 Javascript 内存管理还很陌生,目前正在阅读:

https://www.ibm.com/developerworks/library/wa-memleak/wa-memleak-pdf.pdf

在本文中,对于 Listing5,解释如下:

In Listing 5 you see a closure in which a JavaScript object (obj) contains a reference to a DOM object (referenced by the id "element"). The DOM element, in turn, has a reference to the JavaScript obj. The resulting circular reference between the JavaScript object and the DOM object causes a memory leak.

任何人都可以给我一些关于此模式如何建立循环引用并导致内存泄漏的更多详细信息(图表将不胜感激)?特别是这一部分:

The DOM element, in turn, has a reference to the JavaScript obj.

document.write("Program to illustrate memory leak via closure");

window.onload = function outerFunction() {
    var obj = document.getElementById("element");

    obj.onclick = function innerFunction() {
        alert("Hi! I will leak");
    };

    obj.bigString = new Array(1000).join(new Array(2000).join("XXXXX"));
    // This is used to make the leak significant
};
<button id="element">Click Me</button>

最佳答案

仅当您计划在某个时候删除按钮元素时才会出现问题。

循环引用的发生是由于outerFunction导致的闭包:innerFunction是按钮的点击事件监听器,将引用obj 这是按钮。因此,删除按钮不会生效,因为对它的引用始终存在(在其自己的单击事件监听器内),从而阻碍垃圾收集器。

当对象不再有任何引用时,垃圾收集器会在 JS 中删除该对象。从 DOM 中删除按钮,例如:

document.getElementById("element").remove();

将从 DOM 中删除对该按钮的引用,但垃圾收集器将无法删除它,因为 innerFunction 内将有另一个对该按钮的引用,即 obj (包含对按钮的引用)。

这里的循环引用是,为了删除/销毁innerFunction,必须首先销毁按钮,并且为了删除/销毁按钮,必须删除对它的所有引用,包括innerFunction 内的一个。

注意:在最近的浏览器中,您shouldn't worry关于那些导致内存泄漏的事件监听器。

关于javascript - 该模式如何获得循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49931658/

相关文章:

javascript - 根据 php 响应更改 href

python - 重复 os.path.isdir 调用中的巨大内存泄漏?

.net - 我的内存去哪儿了?大的私有(private)字节数

Internet Explorer 中的 Javascript 命名函数表达式

javascript - 简写 css 属性列表

javascript - Material Ui 代码在 codepen 中运行良好,但在 VSCODE 中运行不佳?

java - 如何在scala中不使用collec()将RDD[CassandraRow]转换为List[CassandraRow]

javascript - 添加数据后,我从 Firestore 获取重复数据。在 React Native 中

javascript - Ionic(或 Angular )中的内存泄漏?

memory-leaks - AVPlayer 的 init 方法是否存在泄漏?