Type Checking?

A little unsure about the most efficent way to type check.

I wanted to write a little utility to handle type checking like this

var _typeCheck = function(obj, type){ 
      if (obj instanceof Object) {
	    return {}.toString.call(obj) === '[object '+type+']'; 
	  } else throw 'Error: Object expected!';
};

var _isFunction = function(obj){ return _typeCheck(obj, 'Function'); };

var _isArray = function(obj){ return _typeCheck(obj, 'Array'); };

I’m wondering if it’s a good idea or not.

For instance in the case of a Function, which would be better

if (typeof Fn !== ‘function’) or if ({}.toString.call(Fn) !== ‘[object Function]’)

RLM

I assume this is because typeof doesn’t give the expected types for arrays and null.

You could also use the constructor property:

var a = function() {alert('a')}
var b = [1,2,3];
var c = 'c';
var d = {a:1};
var e = 123;

print(a.constructor);
// etc.

The result in Firefox:


function Function() {     [native code] }
function Array() {     [native code] }
function String() {     [native code] }
function Object() {     [native code] }
function Number() {     [native code] }

It would be easy enough to parse that string. That said, Crockford suggests using instanceof as well to fix typeof, so perhaps just use the code he provides.

Thanks Raffles,

No the question wasn’t really with regards the difference in results.

Let’s take function as an example. typeof, {}.toString.call and constructor will all do the trick. Which is the most efficient/reliable choice though?

I’m guessing performance wise constructor as it’s a simple look-up?

Thanks for the link by the way. Maybe some answers in there:)

Cheers

RLM

Edit: I’m thinking, until it breaks, I might as well just go with this then.

var _isFunction = function(obj){ return (obj && obj.constructor === Function);};

var _isArray = function(obj){ return (obj && obj.constructor === Array);};

Simple enough.