6

In Javascript you can delete an object property:

var o = { x: 1, y: 2 };

var wasDeleted = delete o.x;

Now o.x should be undefined and wasDeleted is true.

However you can only delete native objects, and unfortunately the browsers seem to have different ideas on this:

window.x = 1;

delete window.x;

Now in Chrome and IE9-10 x will be undefined, but in IE6-8 this throws an exception:

"Object doesn't support this action"

Great. Note that this isn't that delete is unsupported...

// Oops, no var, so this is now a global, should've 'use strict'
o = { x: 1, y: 2 };

// Works
delete o.x;

// Works
delete window.o.y;

// Fails, but only in IE6-8 :-(
delete window.o

I realise that I can add a try {...} catch block, but...

Is there any way to check whether a browser supports delete against a particular object before it is called?

I.e. can I tell whether a property is considered host or native by the browser?

Sam Hanley
  • 4,707
  • 7
  • 35
  • 63
Keith
  • 150,284
  • 78
  • 298
  • 434
  • Host objects (such as *window*) are not required to behave like native objects (like instances of Object). When dealing with host objects (such as DOM objects), you should use methods specified in that object's interface because deleting a property of a host object may have significant consequences not accounted for in the language (ECMAScript) specification (e.g. deleting the *checked* property of an input element). – RobG Jun 19 '13 at 10:58
  • @RobG I get that, the odd bit is that (in IE6-8 only) `window.o.x` is considered to be a native property while `window.o` is considered to be host one. What I want to do is detect (without `try-catch`) which one the browser thinks it is. – Keith Jun 19 '13 at 11:07

1 Answers1

2

delete is a basic javascript language feature which also is supported by IE6-8. It's just that these legacy browsers deal differently on deleting imutable or native / host object properties. I'm afraid a try-catch statement is your only option to cover this.

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • I kinda figured something like that - it's odd that you can extend a _host_ object (by accident event, just forget to `var`) but then that global property is sort-of _host_ instead of _native_. There should at least be some way to detect that. – Keith Jun 19 '13 at 10:58
  • @keith—that is a very special case. It is a language feature that assigning to an undefined variable creates a property of the global object. It is a feature of the DOM that there is a *window* object that is more or less an alias for the global object. – RobG Jun 19 '13 at 11:04