ola*_*huy 6 javascript memory-management javascript-events
关于添加/删除DOM对象的侦听器,我有一个简单的问题.我想问一下,当从页面中删除元素时,垃圾收集器是否能够收集内存.
恩.一个<ul>带着孩子的夫妇列表标签(<li>)
var ul = document.getElementById('someParent');
var children = ul.children;
var someFunction = function() {};
for(var i = 0; i < children.length; i++) {
children[i].addEventListener('click', someFunction);
}
// This is where I am not sure, would the garbage collector be able to collect
// the memory allocated on adding listener on children,
// if I remove the ul tag?
ul.remove();
Run Code Online (Sandbox Code Playgroud)
该行将从DOM 中ul.remove();删除元素及其所有子元素。ul但是,只要您引用了这些侦听器、li元素和ul元素,事件侦听器的内存就不会被释放。你确实有变量children和someFunction。ul
如果你想让垃圾收集器清理所有这些,你可以这样做:
ul.remove();
children = null;
someFunction = null;
ul = null;
Run Code Online (Sandbox Code Playgroud)
这样变量children将不会保存对这些元素的引用,并且如果代码中没有任何其他变量来保存这些元素的引用,垃圾收集器将收集它们。这同样适用于someFunction. 请注意,ul元素保存对其子元素和侦听器的所有引用,因此ul也必须进行清理。
| 归档时间: |
|
| 查看次数: |
1079 次 |
| 最近记录: |