Get the name of an object’s type

Get the name of an object’s type

Is there a JavaScript equivalent of Java’s class.getName()?


Solution 1:

Is there a JavaScript equivalent of Java’s class.getName()?


ES2015 Update: the name of class Foo {} is The name of thing‘s class, regardless of thing‘s type, is Builtin constructors in an ES2015 environment have the correct name property; for instance (2) is "Number".

But here are various hacks that all fall down in one way or another:

Here is a hack that will do what you need – be aware that it modifies the Object’s prototype, something people frown upon (usually for good reason)

Object.prototype.getName = function() { 
   var funcNameRegex = /function (.{1,})\(/;
   var results = (funcNameRegex).exec((this).constructor.toString());
   return (results && results.length > 1) ? results[1] : "";

Now, all of your objects will have the function, getName(), that will return the name of the constructor as a string. I have tested this in FF3 and IE7, I can’t speak for other implementations.

If you don’t want to do that, here is a discussion on the various ways of determining types in JavaScript…

I recently updated this to be a bit more exhaustive, though it is hardly that. Corrections welcome…

Using the constructor property…

Every object has a value for its constructor property, but depending on how that object was constructed as well as what you want to do with that value, it may or may not be useful.

Generally speaking, you can use the constructor property to test the type of the object like so:

var myArray = [1,2,3];
(myArray.constructor == Array); // true

So, that works well enough for most needs. That said…


Will not work AT ALL in many cases

This pattern, though broken, is quite common:

function Thingy() {
Thingy.prototype = {
    method1: function() {
    method2: function() {

Objects constructed via new Thingy will have a constructor property that points to Object, not Thingy. So we fall right at the outset; you simply cannot trust constructor in a codebase that you don’t control.

Multiple Inheritance

An example where it isn’t as obvious is using multiple inheritance:

function a() { = 1;}
function b() { = 2; }
b.prototype = new a(); // b inherits from a

Things now don’t work as you might expect them to:

var f = new b(); // instantiate a new object with the b constructor
(f.constructor == b); // false
(f.constructor == a); // true

So, you might get unexpected results if the object your testing has a different object set as its prototype. There are ways around this outside the scope of this discussion.

There are other uses for the constructor property, some of them interesting, others not so much; for now we will not delve into those uses since it isn’t relevant to this discussion.

Will not work cross-frame and cross-window

Using .constructor for type checking will break when you want to check the type of objects coming from different window objects, say that of an iframe or a popup window. This is because there’s a different version of each core type constructor in each `window’, i.e.

iframe.contentWindow.Array === Array // false

Using the instanceof operator…

The instanceof operator is a clean way of testing object type as well, but has its own potential issues, just like the constructor property.

var myArray = [1,2,3];
(myArray instanceof Array); // true
(myArray instanceof Object); // true

But instanceof fails to work for literal values (because literals are not Objects)

3 instanceof Number // false
'abc' instanceof String // false
true instanceof Boolean // false

The literals need to be wrapped in an Object in order for instanceof to work, for example

new Number(3) instanceof Number // true

The .constructor check works fine for literals because the . method invocation implicitly wraps the literals in their respective object type

3..constructor === Number // true
'abc'.constructor === String // true
true.constructor === Boolean // true

Why two dots for the 3? Because Javascript interprets the first dot as a decimal point 😉

Related:  What purpose does a

Caveats for all…

All of these are subject to one potential problem, and that is the question of how the object in question was constructed. Here are various ways of building objects and the values that the different methods of type checking will return:

// using a named function:
function Foo() { this.a = 1; }
var obj = new Foo();
(obj instanceof Object);          // true
(obj instanceof Foo);             // true
(obj.constructor == Foo);         // true
( == "Foo");  // true

// let's add some prototypical inheritance
function Bar() { this.b = 2; }
Foo.prototype = new Bar();
obj = new Foo();
(obj instanceof Object);          // true
(obj instanceof Foo);             // true
(obj.constructor == Foo);         // false
( == "Foo");  // false

// using an anonymous function:
obj = new (function() { this.a = 1; })();
(obj instanceof Object);              // true
(obj.constructor == obj.constructor); // true
( == "");         // true

// using an anonymous function assigned to a variable
var Foo = function() { this.a = 1; };
obj = new Foo();
(obj instanceof Object);      // true
(obj instanceof Foo);         // true
(obj.constructor == Foo);     // true
( == ""); // true

// using object literal syntax
obj = { foo : 1 };
(obj instanceof Object);            // true
(obj.constructor == Object);        // true
( == "Object"); // true

While not all permutations are present in this set of examples, hopefully there are enough to provide you with an idea about how messy things might get depending on your needs. Don’t assume anything, if you don’t understand exactly what you are after, you may end up with code breaking where you don’t expect it to because of a lack of grokking the subtleties.


Discussion of the typeof operator may appear to be a glaring omission, but it really isn’t useful in helping to identify whether an object is a given type, since it is very simplistic. Understanding where typeof is useful is important, but I don’t currently feel that it is terribly relevant to this discussion. My mind is open to change though. 🙂

Solution 2:

Jason Bunting’s answer gave me enough of a clue to find what I needed:

<<Object instance>>

So, for example, in the following piece of code:

function MyObject() {}
var myInstance = new MyObject(); would return "MyObject".

Solution 3:

A little trick I use:

function Square(){
    this.className = "Square";
    this.corners = 4;

var MySquare = new Square();
console.log(MySquare.className); // "Square"

Solution 4:


To be precise, I think OP asked for a function that retrieves the constructor name for a particular object. In terms of Javascript, object does not have a type but is a type of and in itself. However, different objects can have different constructors.

Object.prototype.getConstructorName = function () {
   var str = (this.prototype ? this.prototype.constructor : this.constructor).toString();
   var cname = str.match(/function\s(\w*)/)[1];
   var aliases = ["", "anonymous", "Anonymous"];
   return aliases.indexOf(cname) > -1 ? "Function" : cname;

new Array().getConstructorName();  // returns "Array"
(function () {})().getConstructorName(); // returns "Function"


Note: the below example is deprecated.

Related:  Declare multiple variables in JavaScript

A blog post linked by Christian Sciberras contains a good example on how to do it. Namely, by extending the Object prototype:

if (!Object.prototype.getClassName) {
    Object.prototype.getClassName = function () {

var test = [1,2,3,4,5];

alert(test.getClassName()); // returns Array

Solution 5:

Using Object.prototype.toString

It turns out, as this post details, you can use Object.prototype.toString – the low level and generic implementation of toString – to get the type for all built-in types'abc') // [object String] // [object RegExp][1,2,3]) // [object Array]

One could write a short helper function such as

function type(obj){

return [object String] as String
return [object Number] as Number
return [object Object] as Object
return [object Undefined] as Undefined
return [object Function] as Function

Solution 6:

Here is a solution that I have come up with that solves the shortcomings of instanceof. It can check an object’s types from cross-windows and cross-frames and doesn’t have problems with primitive types.

function getType(o) {
function isInstance(obj, type) {
    var ret = false,
    isTypeAString = getType(type) == "String",
    functionConstructor, i, l, typeArray, context;
    if (!isTypeAString && getType(type) != "Function") {
        throw new TypeError("type argument must be a string or function");
    if (obj !== undefined && obj !== null && obj.constructor) {
        //get the Function constructor
        functionConstructor = obj.constructor;
        while (functionConstructor != functionConstructor.constructor) {
            functionConstructor = functionConstructor.constructor;
        //get the object's window
        context = functionConstructor == Function ? self : functionConstructor("return window")();
        //get the constructor for the type
        if (isTypeAString) {
            //type is a string so we'll build the context (window.Array or window.some.Type)
            for (typeArray = type.split("."), i = 0, l = typeArray.length; i < l && context; i++) {
                context = context[typeArray[i]];
        } else {
            //type is a function so execute the function passing in the object's window
            //the return should be a constructor
            context = type(context);
        //check if the object is an instance of the constructor
        if (context) {
            ret = obj instanceof context;
            if (!ret && (type == "Number" || type == "String" || type == "Boolean")) {
                ret = obj.constructor == context
    return ret;

isInstance requires two parameters: an object and a type. The real trick to how it works is that it checks if the object is from the same window and if not gets the object’s window.


isInstance([], "Array"); //true
isInstance("some string", "String"); //true
isInstance(new Object(), "Object"); //true

function Animal() {}
function Dog() {}
Dog.prototype = new Animal();

isInstance(new Dog(), "Dog"); //true
isInstance(new Dog(), "Animal"); //true
isInstance(new Dog(), "Object"); //true
isInstance(new Animal(), "Dog"); //false

The type argument can also be a callback function which returns a constructor. The callback function will receive one parameter which is the window of the provided object.


//"Arguments" type check
var args = (function() {
    return arguments;

isInstance(args, function(w) {
    return w.Function("return arguments.constructor")();
}); //true

//"NodeList" type check
var nl = document.getElementsByTagName("*");

isInstance(nl, function(w) {
    return w.document.getElementsByTagName("bs").constructor;
}); //true

One thing to keep in mind is that IE < 9 does not provide the constructor on all objects so the above test for NodeList would return false and also a isInstance(alert, “Function”) would return false.