How can I make an object if 'auto-delete' in Javascript?

Asked

Viewed 137 times

2

I tried something like:

function Objeto(){
  this.del = function(){
    delete this;
  }
}

var a = new Objeto();

a.del();

But the variable a is still existing


I know the method quoted in the @bfavaretto response, but for the code I am working on I cannot 'move up a level' in the variable structure to run this delete, or obj = null;

This is the section where I want to use this:

Bullet.prototype.step = function() {
    for (var i = 0; i < mobs.length; i++){
        if ((this.x >= mobs[i].x && this.x <= mobs[i].x + mobs[i].size) && (this.y >= mobs[i].y && this.y <= mobs[i].y + mobs[i].size)){
            mobs[i].getHit(this.damage);
            delete this;
        }
    }
};

Or the complete reference:http://codepen.io/GabrielMaia/pen/LEmROB

  • Gabriel, the problem is that the delete does not delete the object but a property of an object. If you test: window.teste = new Object(); delete window.teste;, the reference to the teste but if someone has a reference for it, it is possible to access it.

  • Can you explain better why you’re wanting to do this?

  • It is the basic of a projectile system in a simple game... When a Bullet contact a mob it should disappear, because when many of these are loaded the loss of performance is visible... I intend to make sure that when finding a mob, or the boundaries of the screen, Bullet is destroyed, giving way to a new Bullet in the array Bullets

  • 1

    So all that needs to be done is remove that bullet from the array. Create a function for this, which receives the bullet in question and remove the corresponding position from the array. You can find the position with indexOf, and remove with splice.

  • It Works the/ .

  • 1

    OK @Gabrielmaia, good that it worked! I updated my answer to concentrate the information in one place.

Show 1 more comment

1 answer

5


You can simply define all references to the object as null:

a = null;

But it needs to be all the same. For example:

var b = a;
a = null;
b = null; // não esqueça!

Related question: How the Javascript garbage collector works?


Considering your comment that says it is an array of Bullets, from where you need to remove one of these bullets: create a function to do so, which receives the bullet in question and remove the corresponding position from the array. You can find the position with indexOf, and remove with splice. Something like that:

var bulletArray = []; // considere populada
function removeBullet(bullet) {
    var index = bulletArray.indexOf(bullet);
    bulletArray.splice(index, 1);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.