Finding Out Class Names of JavaScript Objects

JavaScript lacks a built-in function for getting the exact class names of object instances. The typeof operator just returns "object" for instances of both Object and Array, as well as user-defined classes. The following example illustrates this:

function MyClassA() {
}

var obj = new Object();
var arr = new Array();
var myobj = new MyClassA();

document.write(typeof(obj) + "<br/>");
document.write(typeof(arr) + "<br/>");
document.write(typeof(myobj) + "<br/>");

The output of the code above, with your browser is:

The constructor property of a JavaScript object (except for intrinsic objects such as window and document) points to the object’s constructor, which has the same name as the class of the object. The name of the constructor can be obtained by parsing out the function name part from the string representation of the constructor. The following function makes use of this idea to implement a utility function for getting the exact class names of extrinsic objects. It returns undefined for intrinsic objects:

/* Returns the class name of the argument or undefined if
   it's not a valid JavaScript object.
*/
function getObjectClass(obj) {
    if (obj && obj.constructor && obj.constructor.toString) {
        var arr = obj.constructor.toString().match(
            /function\s*(\w+)/);

        if (arr && arr.length == 2) {
            return arr[1];
        }
    }

    return undefined;
}

Following is an example of using the getObjectClass function with several different types of arguments. Note that the document object doesn’t have a constructor property that we can use:

function MyClass() {
}

function test(type, expr) {
    var obj = eval(expr);
    
    document.write("<p>" + type + ": " +
        expr + "<br/>");
    document.write("- toString() returns: " +
        obj.toString() + "<br/>");
    document.write("- typeof() returns: " +
        typeof(obj) + "<br/>");
    document.write("- getObjectClass() returns: " +
        getObjectClass(obj) + "</p>");
}

test("Integer", "42");
test("Boolean", "true");
test("String", "\"Hello World!\"");
test("Function", "MyClass");
test("Regular expression", "/Match this!/");
test("Intrinsic object", "document");
test("Array object", "new Array(1, 2, 3)");
test("Date object", "new Date()");
test("Object object", "new Object()");
test("MyClass object", "new MyClass()");

The output for the above with your browser is:

Notice how the typeof function returns “object” for all three objects that are instantiated from the Array, Object and MyClass classes. The getObjectClass function, on the other hand, can return the actual class names.