Deleting a window property in IE

Viewed 20741

I can't find any information on this issue; why doesn't the following code work in IE?

window.x = 45;
delete window.x;
// or delete window['x'];

IE reports an "object doesn't support this action" error. Does it have anything to do with that iterating over window properties in IE issue?

4 Answers

I would do it this way:

    window[x] = undefined;
    try{
        delete window[x];
    }catch(e){}

Does this help?

window.x = 45;
alert(window.x);
window.x = null;

I tried this in IE and window.x did have a value, which proves it can be set. Setting the value to null is your best bet for clearing it out.

I implemented this solution when dealing with caching my own data - the data wasn't much the the frequency of the cache was such that the memory leak might have become an issue. It's costly, but periodically remapping the object was the easiest way for me to be sure it wasn't getting out of hand.

obj = {a: 1, b: 2, c: 3};
var max;

function unset(obj, key) {
    try {
        delete obj[key];
    } catch (e) {
        obj[key] = undefined;
    }

    max++;

    if(max > 200) {
        var keys = Object.keys(obj);
        var len = keys.length;
        var n_obj = {};
        for(var i = 0; i < len; i++) {
            if(obj.hasOwnProperty(keys[i]) && obj[keys[i]] !== undefined) {
                n_obj[keys[i]] = obj[keys[i]];
            }
        }
        return n_obj;
    }
    return obj;
}

obj; //{a: 1, b: 2, c: 3}
obj = unset(obj, "b"); //{a: 1, b: undefined, c: 3} OR {a: 1, c: 3}
//and then eventually we'll garbage collect and...
obj = unset(obj, "b"); //{a: 1, c: 3}   

Hopefully, that's useful to some!

Related