Vitaliy Isikov
Vitaliy Isikov

Reputation: 3654

Delete instance of a class?

I have a class that was created like this:

function T() {
    this.run = function() {
        if (typeof this.i === 'undefined')
            this.i = 0;
        if (this.i > 10) {
            // Destroy this instance
        }
        else {
            var t = this;
            this.i++;
            setTimeout( function() {
                t.run();
            }, 1000);
        }
    }
}

Then I initialize it like var x = new T();

I'm not sure how to destroy this instance from within itself once if reaches 10 iterations.

Also, I'm not sure how to destroy it externally either, in case I want to stop it before it reaches 10.

Upvotes: 38

Views: 88292

Answers (2)

KingRider
KingRider

Reputation: 2257

Class not same function are different. Not work a delete. Class is system modification.

class SAFunc {
  method1(){
    console.log("1");
  }
  method2(){
    console.log("2");
  }
}
let func  = new SAFunc();
func['method2']()

Try:

  • delete window['func'] -- not work
  • delete eval['func'] -- not work
  • delete window['SAFunc'] -- not work
  • ...
  • ...

Function - command work delete

method1 = function(){
  console.log("func1");
}
function method2() {
  console.log("func2");
}
var SAFunc = { method3: function() { console.log("func3"); } }

Make ur test... Try:

  • delete window['method1']
  • delete window['method2']
  • delete SAFunc['method3']

Good fun! i love programming

Enjoin us ;)

Upvotes: 3

Denys Séguret
Denys Séguret

Reputation: 382274

To delete an instance, in JavaScript, you remove all references pointing to it, so that the garbage collector can reclaim it.

This means you must know the variables holding those references.

If you just assigned it to the variable x, you may do

x = null;

or

x = undefined;

or

delete window.x;

but the last one, as precised by Ian, can only work if you defined x as an explicit property of window.

Upvotes: 49

Related Questions