Fixing instanceof / typeof

Irakli Gozalishvili rfobic at gmail.com
Tue Oct 16 13:19:25 PDT 2012


Most recently I needed that to do polymorphic function dispatch on input argument type. More specifics can be found here:  
https://github.com/Gozala/method/blob/master/core.js#L121-127

This case may be quite exotic, but I remember running into this quite a lot, can't use cases unfortunately. BTW underscore has bunch of this utilities too: http://underscorejs.org/#objects that making me believe it's common enough case.
Regards
--
Irakli Gozalishvili
Web: http://www.jeditoolkit.com/


On Monday, 2012-10-15 at 17:59 , Brendan Eich wrote:

> Just curious: why did you need a nominal type test, rather than a "duck  
> type" test?
>  
> /be
>  
> Irakli Gozalishvili 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 (mailto: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/20121016/01bca3b4/attachment.html>


More information about the es-discuss mailing list