1

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>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
Martin
  • 79
  • 1
  • 6
  • 2
    JS has gabage collection, so you just return from the function and the object is gone because nothing references it. The runtime will clean it up when it wants to. Am I understanding your intent correctly? – ggorlen Jan 27 '22 at 16:33
  • 1
    Why are you using a class here in the first place? – Luca Kiebel Jan 27 '22 at 16:34
  • You right, i can do it without objet, but i'm learning to manipulate objet – Martin Jan 27 '22 at 16:40
  • In writing the **Title**, follow the tips: https://stackoverflow.com/help/how-to-ask – Ali Yaghoubi Jan 27 '22 at 16:54

2 Answers2

2

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

The delete command has no effect on regular variables, only properties.

let x = {a:"a"};
delete x; //won't work
delete x.a; // works

The only way to delete it is by dereferencing it.

ilovecse
  • 321
  • 2
  • 10