/ Published in: JavaScript
                    
                                        
A more useful version of `typeof` and functions to test if a parameter is of a specified type.
                
                            
                                Expand |
                                Embed | Plain Text
                            
                        
                        Copy this code and paste it in your HTML
/****************************************
A more useful version of `typeof` and functions to test if a parameter is of a specified type.
Inspired by http://snipplr.com/view/1996/typeof--a-more-specific-typeof/
Examples:
var u;
is.Undefined(u) //true
is.Number(u) //false
var n=1;
is.Number(n) //true; note that (n instanceof Number) would be false since n is a literal
is.Object(n) //true
/****************************************/
var is = new (function(){
var undefined;
function test(type)
{
return function(o){
return (o instanceof type ||
(o !== undefined && !(o instanceof Object) /*i.e., it's a literal*/ && o.constructor === type));
};
}
this.Undefined = function(o){ return o === undefined; };
this.Null = function(o){ return o === null; };
this.Boolean = test(Boolean);
this.Number = test(Number);
this.String = test(String);
this.RegExp = function(o){ return (o instanceof RegExp); };
this.Date = function(o){ return (o instanceof Date); };
this.Array = function(o){ return (o instanceof Array); };
this.Function = function(o){ return (o instanceof Function); };
this.Object = function(o){ return (o instanceof Object || this.Boolean(o) || this.Number(o) || this.String(o)); };
})();
//note that if argument `o` is an instance of more than one data type (which can happen if you mess with prototypes),
// only the first type tested will be returned
function typeOf(o)
{
for(var type in is){ if(type != "Object" && is[type](o)) return type.toLowerCase(); }
if(is.Object(o)) return "object";
return "";
}
/*
//test all data types
//it's worth noting that, in IE, an HTML element is not considered an instance of Object
var u;
function f(){ this.toString=function(){return "[object f]"} };
var h = document.createElement("div");
var a = [u, null, true, (new Boolean), 1, (new Number), "s", (new String), /r/, (new RegExp), (new Date), [0,1], (new Array),
f, function(){}, (new Function), {}, (new Object), (new f), h];
for(var i=0; i<a.length; i++)
{
console.log(a[i]+" : "+typeOf(a[i]));
}
*/
Comments
 Subscribe to comments
                    Subscribe to comments
                
                