4
In languages such as 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 {
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 calling the method .destrutor()
, ie, this be done automatically when or object is deleted or Garbage-collected?