0

What is the appropriate way to destroy an instance of a "class" in JavaScript? I'm using node to "require" my classes and its prototypes. And I noticed, setting the instance of the class to equal null does not seem to actually destroy the instance.

E.g.:

The class

function coolClass(){
    this.bob = 'Hey, this is Bob. I should be destroyed, right?!';
    this.init();

    console.log('Cool class has been initialized!');
}

coolClass.prototype.init = function(){
    var self = this;
    this.culprit = setInterval(function(){
        console.log(self.bob);
    },1000);
}

exports.coolClass = coolClass;

Creating & attempting to destroy instance

var coolClass = require('coolClass');

var instance = new coolClass();

setTimeout(function(){
    instance = null;
},5000);

My expectations were that once the timer's function was ran, the coolClass instance would be destroyed; however, it seems that I am wrong.

Any ideas on how to completely remove the instances?

Thanks!

Justin
  • 400
  • 1
  • 5
  • 16

2 Answers2

1

Setting the instance of the class to equal null does not seem to actually destroy the instance.

You're only throwing away your reference (variable) to the instance. However, the closure passed to setInterval still has one, so it is not garbage collected.

Any ideas on how to completely remove the instances?

You will need to stop the interval by

clearInterval(instance.culprit);

and then, as soon as instance is out of scope, garbage collector will do its work.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • So clear any intervals and timeouts within the class, and then set the instance variable equal to `null`? – Justin Jan 31 '14 at 01:04
  • Yes, remove any asynchronous callbacks that still reference it, and remove all other references to it. Mostly you won't need to explicitly set it to `null`, as the variable just goes out of scope when the function exits. – Bergi Jan 31 '14 at 01:06
0
> var instance = new coolClass();

creates a new instance of coolClass and assigns a reference to it as the value of instance.

> instance = null;

replaces the value of instance with null, it doesn't do anything to the object formerly referenced by instance, which will continue to exist for at least as long as something has a reference to it (such as the function passed to setTimeout).

At some time after that, it may be garbage collected at the host environment's whim.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Thanks for the answer! This is the solution; however it seems Bergi posted it first. Whenever I gain my reputation to upvote, I'll come back and upvote your answer. I really appreciate it! – Justin Jan 31 '14 at 01:13