Syntax: getClass(obj[, mustBeConstructor:Boolean])
Returns the class of obj.
It gets the class 2 ways: Getting the name of the constructor if the constructor hasn't been modified, which if it has modified (and is therfor invalid to use), it falls back to using Object.prototype.toString to get the class though it won't return the name of the constructor function that created it then. If you absolutely need the constructor's name, pass true as the second argument, and it will reset the constructor if it has been modified, to get the real constructor.
It depends on getFunctionName so I have included that in the source too.
Examples (I also put them in the first comment because I didn't know I could edit the snippet):
function Foo() {}
var bar = new Foo;
getClass(bar) == "Foo"
getClass(bar, false) == "Object" // ignore any constructor
bar.constructor = "trying to hide the constructor"
getClass(bar) == "Object" // doesn't trust constructor property so it uses fallback
getClass(bar, true) == "Foo" // ONLY return the constructor's name (and therefor resets the constructor property if modified)
getClass(window) == "Window"
getClass(undefined) == "undefined"
getClass([]) == "Array"
getClass(null) == "null"
getClass(true) == "Boolean"
getClass(new Date) == "Date"
getClass("foo") == "String"
getClass(5e-324) == "Number"
function getClass(obj, forceConstructor) { if ( typeof obj == "undefined" ) return "undefined"; if ( obj === null ) return "null"; if ( forceConstructor == true && obj.hasOwnProperty("constructor") ) delete obj.constructor; // reset constructor if ( forceConstructor != false && !obj.hasOwnProperty("constructor") ) return getFunctionName(obj.constructor); return Object.prototype.toString.call(obj) .match(/^\[object\s(.*)\]$/)[1]; } function getFunctionName(func) { if ( typeof func == "function" || typeof func == "object" ) var fName = (""+func).match( /^function\s*([\w\$]*)\s*\(/ ); if ( fName !== null ) return fName[1]; }
Comments
Subscribe to comments
You need to login to post a comment.

Forgot to add some examples, here are a few: