Detecting types in JavaScript sucks
This answer discusses the standard way to check the type of a JavaScript object (specifically, an array):
The method given in the ECMAScript standard to find the class of Object is to use the toString method from Object.prototype.
if( Object.prototype.toString.call( someVar ) === '[object Array]' ) { alert( 'Array!' ); }
Why abuse Object.prototype.toString? It turns out that objects created in different frames have different constructors.
typeof only works for objects which are (or have equivalent) primitives, like strings.
Another way?
The above code makes me feel funny inside, and doesn’t have a chance of working for custom types, so I wrote this [Gist]:
function isType(object, type){
return object != null && type ? object.constructor.name === type.name : object === type;
}
You use it like this:
isType([1, 2, 3], Array);
isType(null, null);
isType('foo', String);
mauke on ##javascript points out that it fails for objects whose constructors have the same name as the type you're testing against:
isType(new (function String(){}), String);
I think I like this behavior more than calling every custom type an Object.
To take it one step further
jQuery has a 25-line isPlainObject to tell if something is a plain object ({ foo: 'bar' }).
In what cases does the jQuery version behave more-correctly than…
isType(thing, Object);
?
Disclaimer: I haven’t tested this code in a bunch of cases or in a bunch of browsers. The experience concentrated into the jQuery source could blow me back to preschool.
windowhas its own separate "Array" constructor, for example, and it's entirely possible that the name "Array" is distinct window by window also. – Pointy Oct 10 '11 at 4:06constructorproperty wasn't reliable in a multiwindowenvironment too. – alex Oct 10 '11 at 4:06isType(false, Boolean)– John Flatness Oct 10 '11 at 4:07