简体   繁体   中英

How to delete an object in JavaScript?

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>

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM