Reyraa
Reyraa

Reputation: 4274

How to destroy the instance of a JavaScript class completely?

I have a class with many methods in its prototype and I want to destroy its instance after it's done.
This answer tells how to destroy an instance of a class but I'm not sure which variables and/or other types of references I may have in the instance and it's methods that prevents it from removing by garbage collector.

I know I need to remove closures like the functions passed to setInterval. What would be a list of possible items I need to do to destroy the instance completely?

Upvotes: 2

Views: 10193

Answers (2)

Sagi
Sagi

Reputation: 9294

Set interval will continue running because it can not free the instance (of A) due to a closure to the A function which is the constructor of the class. Therefore you need to create a dispose pattern in order to free all the resources that the garbage collector can not free. After that the instance would be freed by the garbage collector when it is not used anymore.

function A() {  
   this.timerId = setInterval(function(){ 
       console.log("A"); 
   }, 2000)
}

A.prototype.dispose = function() {
  clearInterval(this.timerId);
};

var instance = new A();

/* Will not work
instance = null;
*/

instance.dispose();
instance = null;    

Upvotes: 1

s korhani
s korhani

Reputation: 356

These are items I know you should do:

  1. All the functions passed to setInterval and setTimeout must have declaration so you can remove them by making equal to null.
  2. Use clearInterval and clearTimeout for all of them.
  3. All the closures inside your methods must have declaration - must not be anonymous - in order to be removed.
  4. Make sure you haven't used global variables in so that your methods and closures retain the reference to it.
  5. in the last step make the instance itself equal to null.

hope it covers all you need.

Upvotes: 3

Related Questions