Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete instance of a class?

Tags:

javascript

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.

like image 795
Vitaliy Isikov Avatar asked Jun 21 '13 20:06

Vitaliy Isikov


People also ask

How do I delete all instances in C++?

delete keyword in C++ Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. New operator is used for dynamic memory allocation which puts variables on heap memory. Which means Delete operator deallocates memory from heap.

How do you delete a class object in C++?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

How do you delete a class object in Python?

The del keyword in python is primarily used to delete objects in Python. Since everything in python represents an object in one way or another, The del keyword can also be used to delete a list, slice a list, delete a dictionaries, remove key-value pairs from a dictionary, delete variables, etc.


1 Answers

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.

like image 177
Denys Séguret Avatar answered Sep 24 '22 03:09

Denys Séguret