Fixing instanceof / typeof

Irakli Gozalishvili rfobic at gmail.com
Mon Oct 15 14:59:20 PDT 2012


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/

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20121015/c6cea11c/attachment.html>


More information about the es-discuss mailing list