How to dereference and then delete a JavaScript object correctly?

I would like to know the correct way to completely dereference a JavaScript object from memory. To ensure that it is deleted without being stuck in memory and that the garbage collector deletes the object.

When I looked and this question is Removing objects in JavaScript . It was explained that if you delete all references to an object, GC will delete it from memory. I want to know how I can remove links from an object that has both methods and properties.

Suppose you have an object created using function , and the object has both methods and properties. Let's say it looks something like this:

 function myObject(x, y) { this.x = x; this.y = y; this.myMethod = function() { // method code } } var myInstance = new myObject(24, 42) // How to remove this completely? 

Note. This is an example, I understand that you can use prototype for methods.

I know I cannot just say delete myInstance . Therefore, in this case, to completely delete the object, I need to call delete for all its properties, and then call delete in the instance, for example?

 delete myInstance.x; delete myInstance.y; delete myInstance; // I'm not sure if this is necessary. 

Will this work? Or do I also need to delete its methods (and if so, how)?

Or maybe there is a better and easier way to do this?

+7
javascript garbage-collection memory-management object dereference
source share
1 answer

Javascript is a garbage collection. It will clear the object ONLY when there is no other code that has a link to it. These other links should either go out of scope (and not be held back by closing), or you can set these other variables to something else so that they do not point to your object. When there are no other variables with a reference to your object, it will be automatically taken care of by the garbage collector, including any of its properties (provided that none of these properties is the object itself to which there is a link), but even then the host object will be cleared , and only the object in the property will continue to live).

You cannot delete an object in any other way in Javascript.

So, to remove the object he created:

 var myInstance = new myObject(24, 42) // How to remove this completely? 

Just clear myInstance as follows:

 myInstance = null; 

You do not need to manually delete add properties from myInstance . If no one is referencing the mother object, and none of the properties are objects that someone has a reference to, then the garbage collector will simply clear everything for you.

The delete operator is primarily intended to remove the properties of an object when you want the parent object to remain (for example, when you just want to delete a property).

+8
source share

All Articles