Fixing instanceof / typeof

# Irakli Gozalishvili (13 years ago)

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)]"

-- Irakli Gozalishvili Web: www.jeditoolkit.com

# Andrea Giammarchi (13 years ago)

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

# Brendan Eich (13 years ago)

Just curious: why did you need a nominal type test, rather than a "duck type" test?

# Irakli Gozalishvili (13 years ago)

Most recently I needed that to do polymorphic function dispatch on input argument type. More specifics can be found here:
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: underscorejs.org/#objects that making me believe it's common enough case.

-- Irakli Gozalishvili Web: www.jeditoolkit.com