Re: Detecting the "type" of a DOM object

Le 06/06/2012 20:59, Boris Zbarsky a écrit :
> There's a common problem where someone has an object and they would
> like to tell whether it's a Node (or an Array or a Date or whatever). 
> Right now, the way to do that is to use instanceof....
ECMAScript 5.1 defines that objects have a [[Class]] internal property.
This is what was used to reliably decide whether an Array is an array.
The only way to reflect [[Class]] is through Object.prototype.toString.
Array.isArray can be polyfilled in ES3 environments as follow:

    Array.isArray = function(x){
       return Object.prototype.toString.call(x) === '[object Array]';
    }

Alternatively, the [[Class]] can be regexped out from the string.
(for the record, in ES.Next, [[Class]] is being renamed to
[[NativeBrand]], but is the same thing)

The equivalent is possible now for DOM elements
(Object.prototype.toString.call(document) returns "[object
HTMLDocument]"), although to know whether something is a Node, you need
to know all possible subclasses.


> but with a huge caveat: you have to pull the Node or Array or whatnot
> off the right global object.
>
> I was wondering whether it would make sense to expose, on DOM
> constructor objects, a method that lets you test whether some other
> object is of that type.  Note that this functionality is already
> present to some extent because the actual methods on the proto have to
> test that the |this| is of the right type.
>
> So you would be to do something like Node.isInstanceOf(myobj) (or
> something along those lines) and this would return true if myobj is a
> Node, even if it's a Node from a different global.
While it wouldn't be perfectly future-proof (since new subclass of Nodes
can come along later), the technique I've explained above does work
across globals.

> Thoughts?  This is somewhat similar to the Array.isArray thing ES
> already has...
For the sake of future-proofness, I agree. I don't like isInstanceOf,
but I don't have a better proposition.

David

Received on Wednesday, 6 June 2012 21:23:01 UTC