How to implement a destructor in JavaScript?

4

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 this class is destroyed. How to do this in JavaScript? For example:

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

document.addEventListener("DOMContentLoaded",function(even){ 
  
  var obj = new minhaClasse(document.getElementById("bt"));
document.getElementById("bt2").addEventListener("click",function(){
    obj.destrutor();
    delete obj;
    
  });
});
<button id="bt">Clique</button>
<button id="bt2">Deletar</button>
<div id="log"></div>

You can remove the event without having to call the .destrutor() method, that is, this is done automatically when the object is deleted or garbage-collected     

asked by anonymous 06.07.2016 / 15:32

1 answer

6

The only way is to call in the same hand. Your code is correct and it will have to be this way.

There is no feature available in the language that allows this. And as far as I know, there is no prospect of having it. This is probably a failure.

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

    
06.07.2016 / 15:38