How to implement a destructor in JavaScript?


In languages ​​like C++, we have the possibility to declare a destructor for a class, so that certain actions are performed when an object of that class is destroyed. How to do this in JavaScript? For example:

class minhaClasse {
    this.elem = elem;
    this.elem.addEventListener("click", this.acao);
    document.getElementById("log").innerHTML += "Clicado !<br/>";
    this.elem.removeEventListener("click", this.acao);

  var obj = new minhaClasse(document.getElementById("bt"));
    delete obj;
<button id="bt">Clique</button>
<button id="bt2">Deletar</button>
<div id="log"></div>

Is there a way to remove the event without having to call the .destrutor() method, that is, this will be done automatically when the object is deleted or garbage-collected ?


The only way is to call in hand. Your code is correct and will have to be so.

There is no feature available in the language that allows this. And as far as I know there is no forecast to have it. This is probably a glitch.

See if it helps you. Note that you can save a line, but you still need to explicitly delete the object, which is not what C++ does.

Scroll to Top