¿Cómo se crea un objeto que puede matarse/eliminarse a sí mismo? p.ej
var bullet = []; function bullet() { this.removeSelf = () => { this = false; } } function setup() { bullet[0] = new Bullet(); bullet[0].removeSelf(); } setup();
No estoy seguro si entendí tu pregunta correctamente, pero si quieres destruir el objeto y liberar la memoria, primero debes eliminar todas las referencias y luego el recolector de basura automáticamente hará el trabajo por ti.
Está almacenando una referencia al objeto en la matriz para que pueda hacer esto: bullet[0] = null
Si el objetivo es eliminarlo de la matriz principal, debe editar esa matriz. Entonces, podemos pasar el padre a la instancia y hacer que removeSelf
busque su instancia en el padre y lo splice
.
También cambié el nombre del constructor a Bullet
.
var bullets = []; function Bullet(parent) { this.removeSelf = () => { const index = parent.indexOf(this); parent.splice(index, 1); } } function setup() { bullets[0] = new Bullet(bullets); bullets[1] = new Bullet(bullets); // Add a second isntance to the array bullets[0].removeSelf(); } setup(); console.log(bullets.length) // Should be 1