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

2

I tried something like:

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

var a = new Objeto();

a.del();

But the a variable is still existing

I know the method mentioned in @bfavaretto's response, but for the code I'm working on I can not 'raise a level' in the variable structure to execute this delete , or obj = null ;

Here's 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: link

    
asked by anonymous 25.02.2015 / 18:17

1 answer

5

You can simply set all object references to null :

a = null;

But it must all be the same. For example:

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

Related question: How does the JavaScript garbage collector work?

Consider your comment that says it is an array of bullets , from where you need to remove one of these bullets: create a function for it, receive the bullet in question and remove the corresponding position from the array. You can find the position with indexOf , and remove with < a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice"> splice . Something like this:

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