Discussion:
typeName() function -- introspecting object types
Per Cederberg
2011-01-10 10:52:58 UTC
Permalink
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:

https://github.com/cederberg/mochikit/commit/582a51531f68a17aa0ddea41df5957cd09424a25

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]

Notes:
[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.

Cheers,

/Per
--
You received this message because you are subscribed to the Google Groups "MochiKit" group.
To post to this group, send email to ***@googlegroups.com.
To unsubscribe from this group, send email to mochikit+***@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mochikit?hl=en.
Loading...