Skip to content

Instantly share code, notes, and snippets.

@eligrey
Created July 21, 2009 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eligrey/151127 to your computer and use it in GitHub Desktop.
Save eligrey/151127 to your computer and use it in GitHub Desktop.
function getClass(obj, useNative) {
return Object.prototype.toString.call(obj, useNative)
.match(/^\[object\s(.*)\]$/)[1];
}
function Foo(){}; // new foo == "[object Foo]"
var Bar = function(){}; // new Bar == "[object Object]"
Bar.name = "Foo"; // toStringX doesn't rely on function.name so this won't matter
var tests = ["new Foo", "new Bar", "123", '"a string"', "false", "new Function"],
results = [];
for (var i=0; i<tests.length; i++) {
results.push("getClass(" + tests[i] + ") == " + getClass(eval( tests[i] )));
}
results.push("getClass(new Foo, true) == " + getClass(new Foo, true))
alert(results.join("\n\n"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment