4

I was surprised to discover that in Firefox console:

> document.mozPointerLockElement
> null
> 'mozPointerLockElement' in document
> true
> document.hasOwnProperty('mozPointerLockElement')
> false

Whereas in Chrome console equivalent hasOwnProperty() test returns true:

> document.webkitPointerLockElement
> null
> 'webkitPointerLockElement' in document
> true
> document.hasOwnProperty('webkitPointerLockElement')
> true

Does HTML standard specify which properties of a document should be direct and can be reliably tested with hasOwnProperty() or are all such tests implementation dependent and not portable?

Jan Wrobel
  • 6,969
  • 3
  • 37
  • 53
  • 3
    It's hard to know conclusively that something doesn't exist, but I'd be very surprised if that behavior was covered by a standard. The `.hasOwnProperty()` function is a JavaScript thing, and the DOM really has nothing to do with JavaScript. They don't even use JavaScript syntax to describe the APIs. – Pointy Feb 22 '14 at 14:35
  • 1
    In _FireFox_ it's on `proto(proto(document)); // DocumentPrototype`, I believe there is very little spec-wise saying how _Host Objects_ such as `window` and `document` actually have to be implemented, just what they should implement. – Paul S. Feb 22 '14 at 14:41
  • 1
    As a general rule of thumb I'd just say for _host Objects_, check using `in`, for _native objects_ (esp. `instanceof`s), check using `hasOwnProperty`. If you want to know the difference; http://stackoverflow.com/a/7614380/1615483 – Paul S. Feb 22 '14 at 14:50

1 Answers1

3

Does HTML standard specify which properties of a document should be direct and can be reliably tested with hasOwnProperty()

Yes, WebIDL does specify this. In your case, there should be a getter property (as pointerLockElement is a readonly attribute) on the document.prototype (because it was not declared [Unforgeable]).

or are all such tests implementation dependent and not portable?

However, I don't know whether all browsers do adhere that spec - certainly there are some that don't. Also, you're testing vendor extensions in your example (prefixed with moz or webkit) and I don't know whether their behaviour is specified at all. If you want to test against the prototypes, notice that there are implementation differences as well.

So, your best bet is the in operator which detects all properties, regardless whether they're defined on the object itself or one of its prototypes. You might also try !== undefined, as nullable properties would return null instead of undefined.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375