0

I used to create instances of my JavaScript "classes" using the new keyword and call the constructor like: 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();

I come to think about the memory management: does JS clean up the objects without references when they aren't used anymore? - 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. Then I decide to delete the window from the DOM. How can I make sure the actual object is removed as well?

5
  • What do you mean by "the actual object" in "How can I make sure the actual object is removed as well?" What "actual object?" Commented Apr 28, 2012 at 14:33
  • With the object I mean, the instance that was created with the new keyword. In this instance DOM nodes were created, but the object it self "this", is what I mean; the instance. Commented Apr 28, 2012 at 14:36
  • It would be helpful if you could include some code in your example to clarify exactly what you're asking. Almost certainly the answer is "yes, the objects are cleaned up." Commented Apr 28, 2012 at 14:43
  • I don't have any code example really, it's just a general thought. I know in some other languages, or other situations when you save the actual instance to a variable as reference, it's said to be a good idea to set it to null when it's not used anymore. But in these cases when you create an unknown number of instances without references of course, there's no way to set it to null that I know of. Commented Apr 28, 2012 at 14:52
  • An instance cannot be null, only a reference. If there is no reference to an instance, there is nothing to set to null. Commented Apr 28, 2012 at 16:06

1 Answer 1

2

Does JS clean up the objects without references when they aren't used anymore?

Yes. JavaScript is a garbage collected language.

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. Certain DOM implementations (such as in older versions of IE) are notorious for leaking memory in this way. Other browsers/DOM implementations may not have such bugs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.