Search code examples
javascriptclassobjectinstances

Deleting an instance of a JavaScript Object


I have a JavaScript Object called box_brick:

function box_brick( attribute1, attribute2, etc )
{
    this.attribute_1 = attribute1;
    this.attribute_2 = attribute2;
    this.attribute_etc = etc;

    box_brick.instances.push(this);
}

I create new box_bricks by declaring them:

var box_62 = new box_brick('new attribute 1', 'new attribute 2', 'etc');

This works well for my application, and gives me box_brick.instances:

enter image description here

The way my code is set up, each time a new box is created, I have both the instance in box_brick.instances, as well as a standalone object, which I can then call directly to get information from. For example, to get brick_60's color, I can just invoke brick_60.box_color, and in this case I would receive '#ff008c'.

(These may be one and the same -- I am still a little unclear on the difference between objects, instances, classes, and so on, for which I apologize)

For the life of me I cannot figure out how to delete one of these box_bricks from the box_brick.instances -- for example, if I wanted to delete brick_60, so that it's not longer in box_brick.instances, I'm not sure how I would go about doing it.

I've tried doing brick_60.delete, delete(brick_60); and many other things, but am fully stumped.

Any guidance would be greatly appreciated.


Solution

  • In ES6, use a Set.

    ES6 sets are "bags" of things which are there or not. Unlike an array, which you have to iterate over to find something, with sets, you can just add and delete items directly. They are pre-indexed by their contents, as it were.

    // constructor
    function box_brick( attribute1, attribute2, etc )
    {
        ...
        box_brick.instances.add(this);
                            ^^^^^^^^^      // add to set
    }
    
    // initialize set
    box_brick.instances = new Set();
    
    // create a new instance
    box_brick_instance = new box_brick(...);
    
    // remove it from the set
    box_brick.instances.delete(box_brick_instance);
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^    // delete from set