Fixing instanceof / typeof

Andrea Giammarchi andrea.giammarchi at gmail.com
Mon Oct 15 17:29:52 PDT 2012


you have a getClass mechanism but no getImplementedInterfaces one ... also
never thought about xpcomponents but at least I would speed up that
function via {}.toString.call .... rather than that double lookup per each
call :-)

However, xpconnect is a very specific use case so you might decide to
RegExp that if really needed or split by ( and )

Sorry could not help that much

On Mon, Oct 15, 2012 at 2:59 PM, Irakli Gozalishvili <rfobic at gmail.com>wrote:

> Hi,
>
> Today I had to deal with a value type detection in JS and that reminded me
> of all the pain associated with it, especially when dealing with values
> that may have come across the diff compartment / frame / context.
> `instanceof` is useless when dealing with objects from diff contexts,
> `typeof` is also pretty limited in a sense that it can detect weather value
> is array, error, map, set, etc.. not to mention it's awkwardnesses…
>
> Only solution that seems to work toady that is adopted by most popular JS
> libraries is:
>
> function type(value) {
>   return Object.prototype.toString.call(value).split('
> ')[1].split(']')[0].toLowerCase()
> }
>
> I don't actually know if that's supposed to work according to spec or if
> it's just an implementation coincidence that happen to
> work. Either way I would really welcome some standard
> solution preferably  via function form (so that can be polyfilled today)
> to do type detection for all the built-ins and host objects.
>
> Aside main issue, it would be great if solution was compatible with
> mozilla's xpcom components too where one object my be
> queried with multiple interfaces and there for have multiple types. Also,
> above hack does not works with XPCOMs as  Object.prototype.toString returns
> "[object XPCWrappedNative_NoHelper]", while actual toString returns
> something little more useful "[xpconnect wrapped (nsISupports, nsIURI,
> nsIURL)]"
>
> Regards
> --
> Irakli Gozalishvili
> Web: http://www.jeditoolkit.com/
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20121015/abb99135/attachment.html>


More information about the es-discuss mailing list