type.of() - a more specific typeof()

The type.of ECMAScript (JavaScript) function is meant to be of help in identifying correctly the type of anything placed as an argument.

You can click the following link to see the code snippet in Snipplr.

type.of() - a more specific typeof()
Posted by rolandog on January 17th, 2007
Helps identify correctly the type of whatever you put as an argument. This was adapted from http://www.planetpdf.com/developer/article.asp?ContentID=testing_for_object_types_in_ja

  1. var is={
  2.         Null:function(a){
  3.                 return a===null;
  4.         },
  5.         Undefined:function(a){
  6.                 return a===undefined;
  7.         },
  8.         nt:function(a){
  9.                 return(a===null||a===undefined);
  10.         },
  11.         Function:function(a){
  12.                 return(typeof(a)==='function')?a.constructor.toString().match(/Function/)!==null:false;
  13.         },
  14.         String:function(a){
  15.                 return(typeof(a)==='string')?true:(typeof(a)==='object')?a.constructor.toString().match(/string/i)!==null:false;
  16.         },
  17.         Array:function(a){
  18.                 return(typeof(a)==='object')?a.constructor.toString().match(/array/i)!==null||a.length!==undefined:false;
  19.         },
  20.         Boolean:function(a){
  21.                 return(typeof(a)==='boolean')?true:(typeof(a)==='object')?a.constructor.toString().match(/boolean/i)!==null:false;
  22.         },
  23.         Date:function(a){
  24.                 return(typeof(a)==='date')?true:(typeof(a)==='object')?a.constructor.toString().match(/date/i)!==null:false;
  25.         },
  26.         HTML:function(a){
  27.                 return(typeof(a)==='object')?a.constructor.toString().match(/html/i)!==null:false;
  28.         },
  29.         Number:function(a){
  30.                 return(typeof(a)==='number')?true:(typeof(a)==='object')?a.constructor.toString().match(/Number/)!==null:false;
  31.         },
  32.         Object:function(a){
  33.                 return(typeof(a)==='object')?a.constructor.toString().match(/object/i)!==null:false;
  34.         },
  35.         RegExp:function(a){
  36.                 return(typeof(a)==='function')?a.constructor.toString().match(/regexp/i)!==null:false;
  37.         }
  38. };
  39.  
  40. var type={
  41.         of:function(a){
  42.                 for(var i in is){
  43.                         if(is[i](a)){
  44.                                 return i.toLowerCase();
  45.                         }
  46.                 }
  47.         }
  48. };

I was inspired by reading an article in Planet PDF written by Kas Thomas’. The article is called Testing for Object Types in JavaScript.

Post a Comment

*Required
*Required (Never published)