[SOLVED] How to delete an object in JavaScript?

Issue

I have a function which creates an object and I would like to delete it.
I saw this post :
Deleting Objects in JavaScript
but I failed to create condition to delete it.

class setBackgroundColor {
    constructor (element, options) {
        this.element = element;
        this.options = options;
        this.element.style.backgroundColor = this.options;
    }
}

function onWindowResize () {
        let mobile = window.innerWidth < 800
        if (mobile) {
            new setBackgroundColor(document.querySelector('.my_container'), "red")
            // var newObjet = new setBackgroundColor(document.querySelector('.my_container'), "red")
        } else { 
            return 
            // delete newObjet
        }
}        

onWindowResize ();
window.addEventListener('resize', onWindowResize);
.my_container{
    margin: 30px;
    width: 100px;
    height: 100px;
    border: 1px solid black;
}

<div class="my_container"></div>

Solution

The only way to delete an object is to remove all references for it.

The object created by your call to setBackgroundColor is deleted almost immediately because you never keep a reference to it.

If you were to uncomment the line starting \\ var newObjet then it would still be deleted almost immediately because the function would finish and the variable would drop out of scope.


I think that what you want to do is to remove the background colour setting your did.

That isn’t part of the object. The function that did it was just attached to the object, but the change was to the element you passed in, not to the object itself.

If you want to change the background colour to something else then you need to do so explicitly.

else {
    document.querySelector('.my_container').style.backgroundColor = "";

That said, if you want to change the style of something based on the window size, use the media query feature built into CSS.

It is a lot less hassle than searching the DOM and modifying the style with JS.

Answered By – Quentin

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.