views:

250

answers:

5

Hi,

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?

Thanks and best regards

A: 

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.

Sohnee
Unfortunately this doesn't remove the variable from memory, it just gives it a null value, but this is the only option as far as I can tell.
Andy E
Thanks. I've gone a step further and used window.x = undefined. This still isn't what I want, but it'll do. It's strange that I haven't found any useful information on the web about this.
gasper_k
A: 

See Deleting Objects in JavaScript for some good information. I suspect you will have the same issue in Firefox, based on the Mozilla Developer Center Special Operators - MDC article. It says:

You can use the delete operator to delete variables declared implicitly but not those declared with the var statement

Since variables declared with var are also available as properties on the window object, this maybe why you can't delete them.

Kevin Hakanson
Thanks, I've seen the link before, but it's not that related.Also, I'm not having any problem in Firefox 3.0.11 with any of var x, window.x or window['x'] with any of delete x, delete window.x and delete window['x']. Everything works as I think it should.
gasper_k
+1  A: 

I would do it this way:

    window[x] = undefined;
    try{
        delete window[x];
    }catch(e){}
thanks, that's what I did in the end. It throws an exception in IE, but it's caught and no damage is done.
gasper_k
A: 

Hi, I have the same problem. What was the final conclusion? Tx, Sty

I went with:try { delete window[x]; } catch(e) { window[x] = undefined; }
gasper_k
+1  A: 

Gasper made a comment with the solution he finished on, but I think its worth calling out as an actual answer:

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

Interesting issue, I was just banging my head against it tonight. The exception is thrown on IE but not Firefox. I would suspect this workaround leaks memory, so use sparingly.

Frank Schwieterman