user1121487
user1121487

Reputation: 2680

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(); 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?

Upvotes: 0

Views: 442

Answers (1)

Matt Ball
Matt Ball

Reputation: 359906

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.

Upvotes: 2

Related Questions