Posted By

Sephr on 02/23/09


Tagged

class constructor


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

korzhik
enajenkins


getClass


 / Published in: JavaScript
 

getClass

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"
  1. function getClass(obj, forceConstructor) {
  2. if ( typeof obj == "undefined" ) return "undefined";
  3. if ( obj === null ) return "null";
  4. if ( forceConstructor == true && obj.hasOwnProperty("constructor") ) delete obj.constructor; // reset constructor
  5. if ( forceConstructor != false && !obj.hasOwnProperty("constructor") ) return getFunctionName(obj.constructor);
  6. return Object.prototype.toString.call(obj)
  7. .match(/^\[object\s(.*)\]$/)[1];
  8. }
  9.  
  10. function getFunctionName(func) {
  11. if ( typeof func == "function" || typeof func == "object" )
  12. var fName = (""+func).match(
  13. /^function\s*([\w\$]*)\s*\(/
  14. ); if ( fName !== null ) return fName[1];
  15. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Sephr on February 23, 2009

Forgot to add some examples, here are a few:

function Foo() {}
var bar = new Foo;
getClass(bar) == "Foo"
bar.constructor = "trying to hide the constructor"
getClass(bar) == "Object"
getClass(bar, true) == "Foo"

You need to login to post a comment.