Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a window property in IE

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?

like image 252
gasper_k Avatar asked Jul 02 '09 09:07

gasper_k


People also ask

How do I delete a property?

Click Admin, and navigate to the property you want to delete. In the PROPERTY column, click Property Settings. Click Move to Trash Can. On the confirmation screen, click Move property to Trash Can.

How do I remove all properties of an object?

Use a for..in loop to clear an object and delete all its properties. The loop will iterate over all the enumerable properties in the object. On each iteration, use the delete operator to delete the current property. Copied!

How do I remove a property name from an object?

The delete operator is used to remove these keys, more commonly known as object properties, one at a time. The delete operator does not directly free memory, and it differs from simply assigning the value of null or undefined to a property, in that the property itself is removed from the object.


1 Answers

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.

It was asked, why not just assign undefined? It matters if you want to enumerate the keys later (though if you're relying on the workaround, the key enumeration still won't do what you want...). But anyhow, to highlight the difference between delete and simply assigning undefined (http://jsfiddle.net/fschwiet/T4akL/):

var deleted = {     a: 1 };  var cleared = {     a: 1 };  delete deleted["a"]; cleared["a"] = undefined;  for(var key in deleted) {     console.log("deleted has key", key); }  for(var key in cleared) {     console.log("cleared has key", key); }  console.log("deleted has a?", deleted.hasOwnProperty('a')); console.log("cleared has a?", cleared.hasOwnProperty('a')); 

produces output:

cleared has key a deleted has a? false cleared has a? true  
like image 84
Frank Schwieterman Avatar answered Oct 05 '22 06:10

Frank Schwieterman