I created a JavaScript object, but how I can determine the class of that object?
I want something similar to Java\'s .getClass()
method.
This getNativeClass() function returns "undefined"
for undefined values and "null"
for null.
For all other values, the CLASSNAME
-part is extracted from [object CLASSNAME]
, which is the result of using Object.prototype.toString.call(value)
.
getAnyClass()
behaves the same as getNativeClass(), but also supports custom constructors
function getNativeClass(obj) {
if (typeof obj === "undefined") return "undefined";
if (obj === null) return "null";
return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
}
function getAnyClass(obj) {
if (typeof obj === "undefined") return "undefined";
if (obj === null) return "null";
return obj.constructor.name;
}
getClass("") === "String";
getClass(true) === "Boolean";
getClass(0) === "Number";
getClass([]) === "Array";
getClass({}) === "Object";
getClass(null) === "null";
getAnyClass(new (function Foo(){})) === "Foo";
getAnyClass(new class Foo{}) === "Foo";
// etc...