[英]JavaScript, object instance without reference
I used to create instances of my JavaScript "classes" using the new
keyword and call the constructor like: new myStuff.DoSomething();
我曾经使用
new
关键字创建我的JavaScript“类”的实例,并调用构造函数,如: new myStuff.DoSomething();
in order to get an instance of it. 为了获得它的实例。 Sometimes when needed I give the instance a reference like:
var myObj = new myStuff.DoSomething();
有时在需要时我给实例一个引用,如:
var myObj = new myStuff.DoSomething();
I come to think about the memory management: does JS clean up the objects without references when they aren't used anymore? 我开始考虑内存管理:当它们不再使用时,JS是否清理了没有引用的对象? - the same way it would clean up those with references.
- 与清理引用的方法相同。 And what about all event handlers in a killed object, do they still live on?
那个被杀死的物体中的所有事件处理程序呢,它们还能继续存在吗?
Example: If I create, for instance, a draggable window using the new
keyword and no reference to the object and then attach event handlers and so on. 示例:例如,如果我使用
new
关键字创建一个可拖动窗口,并且没有对该对象的引用,然后附加事件处理程序等等。 Then I decide to delete the window from the DOM. 然后我决定从DOM中删除窗口。 How can I make sure the actual object is removed as well?
如何确保删除实际对象?
Does JS clean up the objects without references when they aren't used anymore?
当JS不再使用时,JS是否清理没有引用的对象?
Yes. 是。 JavaScript is a garbage collected language.
JavaScript是一种垃圾收集语言。
And what about all event handlers in a killed object, do they still live on?
那个被杀死的物体中的所有事件处理程序呢,它们还能继续存在吗?
It depends, since we're now talking about the DOM, and not just JS as a language. 这取决于,因为我们现在谈论的是DOM,而不仅仅是JS作为一种语言。 Certain DOM implementations (such as in older versions of IE) are notorious for leaking memory in this way .
某些DOM实现(例如在旧版本的IE中) 以这种方式泄漏内存而臭名昭着 。 Other browsers/DOM implementations may not have such bugs.
其他浏览器/ DOM实现可能没有这样的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.