在javascript上添加/删除监听器(垃圾收集器) [英] add/remove listeners on javascript ( garbage collector )

查看:93
本文介绍了在javascript上添加/删除监听器(垃圾收集器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于添加/删除DOM对象的侦听器的快速问题。
我想询问垃圾收集器是否能够在从页面中删除元素时收集内存。



ex。带有几个孩子列表的< 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);
}


//这是我不确定的地方,垃圾收集器是否能够收集
//为孩子添加监听器时分配的内存,
//如果删除ul标签?
ul.remove();


解决方案

ul.remove (); 将从DOM中删除 ul 元素及其所有子元素。但只要您有对这些侦听器的引用, li 元素和 ul ,就不会释放事件侦听器的内存。元件。变量 children someFunction ul



如果你想让垃圾收集器清理所有这些,你可以这样做:

  ul.remove(); 
children = null;
someFunction = null;
ul = null;

这样变量 children 将不会持有引用这些元素,如果您的代码中没有任何其他变量来保存这些元素的引用,垃圾收集器将收集它们。 someFunction 也是如此。请注意, ul 元素包含对其子项和侦听器的所有引用,因此还必须清除 ul 。 / p>

I have a quick question regarding on adding/removing listeners of a DOM object. I would like to ask if the garbage collector be able to collect the memory when removing elements from the page.

ex. a <ul> tag with a couple list of children(<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();

解决方案

The line ul.remove(); will remove ul element and all of its children from the DOM. But memory for event listeners will not be released as long as you have references to those listeners, li elements, and ul element. Which you do have in variables children, someFunction and ul.

If you want to let the garbage collector clean all of these, you can do for example:

ul.remove();
children = null;
someFunction = null;
ul = null;

That way variable children will not hold the reference to those elements, and if you don't have any other variable in your code that hold the reference for those elements, garbage collector will collect them. The same holds for someFunction. Note that ul element holds all the references to its children and listeners, so ul has to be cleaned as well.

这篇关于在javascript上添加/删除监听器(垃圾收集器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆