typeName() function -- introspecting object types

Skip to first unread message

Per Cederberg

Jan 10, 2011, 5:52:58 AM1/10/11
to moch...@googlegroups.com
Being tired of all the idiosyncrasies of the typeof() operator, I
tried to make something better:

   function typeName(value) {
       if (typeof(value) !== "object" && !(value instanceof RegExp)) {
           return typeof(value);
       } else if (value == null) {
           return "null";
       } else {
           var c = value.constructor || {};
           return c.name || c.NAME || "Object";

See here:


I was thinking about including this in MochiKit.Base, possibly
modifying typeMatcher() on the go. That would break backward
compatibility a bit, so the question is if it would be worthwhile?

This is how typeName() works right now:

 undefined ==> "undefined"
 null ==> "null"
 false ==> "boolean"
 new Boolean(true) ==> "Boolean"
 42 ==> "number"
 new Number(42) ==> "Number" [1]
 "test" ==> "string"
 new String("") ==> "String" [1]
 { a: 1 } ==> "Object" [2]
 [1,2,3] ==> "Array"
 new Date() ==> "Date"
 /\d+/ ==> "RegExp"
 new MyClass() ==> "MyClass" [3]

[1]: There are two forms of these built-in types, but normally the
"constructor" form is not used much.
[2]: These objects constructor actually point to the Object function,
hence the upper-case initial.
[3]: For this to work, the constructor property must be set and the
constructor function must have either a name or a NAME property.



Reply all
Reply to author
0 new messages