Reputation: 1724
function ConstructMe(msg) {
this.message = msg;
}
instances = {
instance1: new ConstructMe('msg1'),
instance2: new ConstructMe('msg2'),
instance3: new ConstructMe('msg3'),
instance4: new ConstructMe('msg4'),
instance5: new ConstructMe('msg5')
}
If I have this Constructor, and I build instances of it in an object (as shown above), how would I go about destroying them later on? I want to make sure that they are no longer accessible, but also to make sure they are no longer somewhere uselessly.
Would deleting the object work? Or the instances would just remain somewhere on the memory nameless?
In my case, I create many instances along certain actions in an app, I want to make sure I keep the memory clean and don't leave things hanging around, cluttering...
Looking forward to your feedback
Upvotes: 1
Views: 4924
Reputation: 5859
The central concept of JavaScript memory management is a concept of reachability.
A distinguished set of objects are assumed to be reachable: these are known as the roots. Typically, these include all the objects referenced from anywhere in the call stack (that is, all local variables and parameters in the functions currently being invoked), and any global variables.
Objects are kept in memory while they are accessible from roots through a reference or a chain of references.
There is a Garbage Collector in the browser which cleans memory occupied by unreachable object
so in your case if your instance of the object will not be reachable any more the garbage collector will automatically delete this object , you don't need to delete them your self or doing any memory management in most of the cases
Upvotes: 1
Reputation: 59397
Javascript does not work that way. It is a garbage collected language. Technically, you can do something like:
delete instances.instance3;
which should remove the property from the instances
object, but in practice you rarely need to worry about it. The JavaScript runtime will take care of cleaning up after you*
*Technically you can still create memory leaks in javascript, but in the vast majority of cases you won't need to worry about it.
Upvotes: 5