HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Alternative implementation of isType()

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementationalternativeistype

Problem

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.

Solution

I could not find anything wrong with your code,
so per Meta I am going to tell you why it is awesome ;)

  • Checking .toString() is icky, toString() could easily be replaced/enhanced



  • Your solution works across frames



  • I was not able to break it.



On a final note, it seems to me that needing to verify the type of an object ( besides assertions ) means you are doing something odd and probably the code should be re-thought.

Still, I am favouriting this question.

UPDATE : Turns out that according to jsperf, your solution is much slower :\

Context

StackExchange Code Review Q#5278, answer score: 5

Revisions (0)

No revisions yet.