本文介绍了JavaScript中的事件处理程序,关闭和垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中没有遇到内存泄漏,但我担心未来可能出现的问题。我想知道如果做这样的事情:

  SomeClass.prototype.someMethod = function(){
var that = this
this。$ div2.click(function(){
that.someMethod2();
});
}

让我们说这个$ div2附加到另一个div这个$ DIV1。如果我打电话给

  this。$ div1.remove(); 

后来失去了我的SomeClass实例的引用,SomeClass实例被收集垃圾?那么HTML元素呢这个。$ div2?这个$ div2不会在DOM里面,因为它被附加到这个$ div1。



我问这个是因为这个$ div2中的事件处理程序可能会保留引用HTML元素这个$ div2,并且还通过关闭来保留对SomeClass的实例的引用,因为变量that。



所以我应该关心正确删除所有的事件和这样的HTML元素?或者简单地删除root元素(这个。$ div1)解决了问题?

解决方案

是的,当所有对它的引用都丢失 - 还有那些通过事件处理程序, - 该实例可以收集垃圾。

它是否附加到DOM是无关紧要的。如果一些不可收集的对象引用 $ div1 ,它也可以访问其子节点 $ div2 ,并且该事件处理程序,所以从处理程序引用的实例不会被收集。

这是循环引用,应该通过引擎处理得好(当外部没有引用对象内的对象可以收集它们时)。但是,当一个DOM对象涉及到该圈子时,(?)Internet Explorers无法执行此操作。



因此,()内部调用,它分离所有的事件监听器。 p>

是的,调用在jQuery包装器上删除会自动删除所有的事件(来自所有子元素)和DOM节点。


I'm not running into a memory leak in my application yet, but I'm worried about possible problems in the future. I would like to know if doing something like this:

SomeClass.prototype.someMethod= function() {
    var that= this
    this.$div2.click(function() {
        that.someMethod2();
    });
}

And lets say that this.$div2 is appended to another div this.$div1. If I call

this.$div1.remove();

and later loses the reference of my SomeClass instance does the SomeClass instance gets garbage collected? And what about the HTML element this.$div2? this.$div2 would not be inside the DOM because it is appended to this.$div1.

I ask this because the event handler in this.$div2 might keep a reference to the HTML element this.$div2 and also keeps a reference to the instance of SomeClass through the closure because of the variable "that".

So should I care about properly removing all events and HTML elements like this? Or simply removing the "root" element (this.$div1) solves the problem?

解决方案

Yes, when all references to it are lost - also those through event handlers , - the instance can get garbage-collected.

It does not matter whether it is currently attached to the DOM. If some non-collectible object references $div1, it also could access its child node $div2 and that one's event handlers, so the instance referenced from the handler would not be collectible.

That's a circular reference and should get handled well by the engines (when none of the objects inside the circle is referenced from outside it can get collected). However, (old?) Internet Explorers fail to do this when a DOM object is involved in the circle.

For that reason the .remove jQuery method (code) internally calls the (internal) cleanData method which detaches all event listeners.

Yes, calling remove on a jQuery wrapper automatically removes all events (from all child elements) and DOM nodes.

这篇关于JavaScript中的事件处理程序,关闭和垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:47