298

Is there any solution to get the function name of an object?

function alertClassOrObject (o) {
   window.alert(o.objectName); //"myObj" OR "myClass" as a String
}

function myClass () {
   this.foo = function () {
       alertClassOrObject(this);
   }
}

var myObj = new myClass();
myObj.foo();

for (var k in this) {...} - there is no information about the className or ObjectName. Is it possible to get one of them?

1

11 Answers 11

494

Get your object's constructor function and then inspect its name property.

myObj.constructor.name

Returns "myClass".

13
  • 231
    Beware! If you're minifying the JavaScript the name of the constructor will change.
    – dB.
    Commented Oct 13, 2012 at 21:00
  • 41
    Handy, but there's another caveat: if your object has a prototype chain (aside from Object), you will get the the name of the first link in that chain, not the name of the constructor used to create the object. Take the following example: function Daddy() {}; function Me() {}; Me.prototype = new Daddy; me = new Me;. me.constructor.name then unexpectedly returns 'Daddy', not 'Me'.
    – mklement0
    Commented Aug 6, 2013 at 20:16
  • 7
    Also worth knowing that the name property is not supported in < IE9
    – Jason
    Commented Oct 25, 2013 at 15:18
  • 11
    And this will return empty string, if used on objects declared through variable: var Foo = function() {};. Commented Feb 26, 2014 at 14:56
  • 3
    The Chrome console knows something you don't: > myclass=(function(){}); new myclass prints myclass {}
    – Hugh Allen
    Commented May 26, 2014 at 4:09
39

Example:

function Foo () { console.log('Foo function'); }
var f = new Foo();
console.log('f', f.constructor.name); // -> "Foo"

var Bar = function () { console.log('Anonymous function (as Bar)'); };
var b = new Bar();
console.log('b', b.constructor.name); // -> "Bar"

var Abc = function Xyz() { console.log('Xyz function (as Abc)'); };
var a = new Abc();
console.log('a', a.constructor.name); // -> "Xyz"

class Clazz { constructor() { console.log('Clazz class'); } }
var c = new Clazz();
console.log('c', c.constructor.name); // -> "Clazz"

var otherClass = class Cla2 { constructor() { console.log('Cla2 class (as otherClass)'); } }
var c2 = new otherClass();
console.log('c2', c2.constructor.name); // -> "Cla2"

Fixed example:

function alertClassOrObject (o) {
   // ::::::: Fixed line
   console.log(o.constructor.name); //"myObj" OR "myClass" as a String
   // ::::::: Fixed line
}

function myClass () {
   this.foo = function () {
       alertClassOrObject(this);
   }
}

var myObj = new myClass();
myObj.foo();

2
  • looks like when using the revealing module pattern, you'll always get "Object". function Foo() { return {'foo':'bar'} }; var f = new Foo(); :(
    – Brad Kent
    Commented Feb 17, 2017 at 16:44
  • 1
    The 'b' log now outputs "Bar" in FF88 and Node (via katacoda.com/courses/nodejs/playground). Seems like anonymous functions now inherit their variable name. And, in case you were wondering, classes use the class name used with new. Commented May 25, 2021 at 5:23
10

As this was already answered, I just wanted to point out the differences in approaches on getting the constructor of an object in JavaScript. There is a difference between the constructor and the actual object/class name. If the following adds to the complexity of your decision then maybe you're looking for instanceof. Or maybe you should ask yourself "Why am I doing this? Is this really what I am trying to solve?"

Notes:

The obj.constructor.name is not available on older browsers. Matching (\w+) should satisfy ES6 style classes.

Code:

var what = function(obj) {
  return obj.toString().match(/ (\w+)/)[1];
};

var p;

// Normal obj with constructor.
function Entity() {}
p = new Entity();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

// Obj with prototype overriden.
function Player() { console.warn('Player constructor called.'); }
Player.prototype = new Entity();
p = new Player();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// Obj with constructor property overriden.
function OtherPlayer() { console.warn('OtherPlayer constructor called.'); }
OtherPlayer.constructor = new Player();
p = new OtherPlayer();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// Anonymous function obj.
p = new Function("");
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// No constructor here.
p = {};
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// ES6 class.
class NPC { 
  constructor() {
  }
}
p = new NPC();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

// ES6 class extended
class Boss extends NPC {
  constructor() {
    super();
  }
}
p = new Boss();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

Result:

enter image description here

Code: https://jsbin.com/wikiji/edit?js,console

Update: Dec 04, 2023

For those needing to grab the class name in IE6 and IE8, obj.constructor exists but name property doesn't exist. So you need to call what(obj.constructor).

enter image description here

2
  • 1
    literally nothing is available on older browsers if you go back far enough
    – ICW
    Commented Dec 2, 2023 at 20:57
  • @ICW can you be more specific? Anyway, I checked constructor property compatibility at caniuse.com/?search=constructor and it seems you are right, at least on IE8 this yields "[object Object]" Commented Dec 4, 2023 at 10:12
5

If you use standard IIFE (for example with TypeScript)

var Zamboch;
(function (_Zamboch) {
    (function (Web) {
        (function (Common) {
            var App = (function () {
                function App() {
                }
                App.prototype.hello = function () {
                    console.log('Hello App');
                };
                return App;
            })();
            Common.App = App;
        })(Web.Common || (Web.Common = {}));
        var Common = Web.Common;
    })(_Zamboch.Web || (_Zamboch.Web = {}));
    var Web = _Zamboch.Web;
})(Zamboch || (Zamboch = {}));

you could annotate the prototypes upfront with

setupReflection(Zamboch, 'Zamboch', 'Zamboch');

and then use _fullname and _classname fields.

var app=new Zamboch.Web.Common.App();
console.log(app._fullname);

annotating function here:

function setupReflection(ns, fullname, name) {
    // I have only classes and namespaces starting with capital letter
    if (name[0] >= 'A' && name[0] <= 'Z') {
        var type = typeof ns;
        if (type == 'object') {
            ns._refmark = ns._refmark || 0;
            ns._fullname = fullname;
            var keys = Object.keys(ns);
            if (keys.length != ns._refmark) {
                // set marker to avoid recusion, just in case 
                ns._refmark = keys.length;
                for (var nested in ns) {
                    var nestedvalue = ns[nested];
                    setupReflection(nestedvalue, fullname + '.' + nested, nested);
                }
            }
        } else if (type == 'function' && ns.prototype) {
            ns._fullname = fullname;
            ns._classname = name;
            ns.prototype._fullname = fullname;
            ns.prototype._classname = name;
        }
    }
}

JsFiddle

0
3

Try this:

var classname = ("" + obj.constructor).split("function ")[1].split("(")[0];
1
  • 2
    Is there any case in which this would be more accurate than obj.constructor.name? I just don't see any reason for this complexity.
    – JHH
    Commented Apr 23, 2019 at 7:50
3

I was facing a similar difficulty and none of the solutions presented here were optimal for what I was working on. What I had was a series of functions to display content in a modal and I was trying to refactor it under a single object definition making the functions, methods of the class. The problem came in when I found one of the methods created some nav-buttons inside the modal themselves which used an onClick to one of the functions -- now an object of the class. I have considered (and am still considering) other methods to handle these nav buttons, but I was able to find the variable name for the class itself by sweeping the variables defined in the parent window. What I did was search for anything matching the 'instanceof' my class, and in case there might be more than one, I compared a specific property that was likely to be unique to each instance:

var myClass = function(varName)
{
    this.instanceName = ((varName != null) && (typeof(varName) == 'string') && (varName != '')) ? varName : null;

    /**
     * caching autosweep of window to try to find this instance's variable name
     **/
    this.getInstanceName = function() {
        if(this.instanceName == null)
        {
            for(z in window) {
                if((window[z] instanceof myClass) && (window[z].uniqueProperty === this.uniqueProperty)) {
                    this.instanceName = z;
                    break;
                }
            }
        }
        return this.instanceName;
    }
}
2

Most efficient way to get your class name during runtime

let className = this.constructor.name

1

All we need:

  1. Wrap a constant in a function (where the name of the function equals the name of the object we want to get)
  2. Use arrow functions inside the object

console.clear();
function App(){ // name of my constant is App
  return {
  a: {
    b: {
      c: ()=>{ // very important here, use arrow function 
        console.log(this.constructor.name)
      }
    }
  }
}
}
const obj = new App(); // usage

obj.a.b.c(); // App

// usage with react props etc, 
// For instance, we want to pass this callback to some component

const myComponent = {};
myComponent.customProps = obj.a.b.c;
myComponent.customProps(); // App

1
  • You could also bind the function to the object to avoid using arrow functions for whatever reason.
    – code
    Commented Dec 29, 2021 at 22:37
0

to get name of class using the class itself.

class Black {
}
// I was search by that and not found in google instade of Black.toString().
console.log(Black.prototype.constructor.name);

// from object ass mentioned by Oleg V. Volkov
const myObj = new Black()
console.log(new Black().constructor.name)

0

What about:

  class Root {
    name() {
      return 'Root';
    }
  }

  class Ext1 extends Root {
    name() {
      return 'Ext1';
    }
  }

  class Ext2 extends Ext1 {
    name() {
      return 'Ext2';
    }
  }
 
  root = new Root();
  ext1 = new Ext1();
  ext2 = new Ext2();

  root.name();  // Root
  ext1.name();  // Ext1
  ext2.name();  // Ext2

It survives bundlers, and ships the functionality you want.

0

After learning from the good answers above, I've made an experiment on google chrome, with the following findings:

The class name may be overriden.

That may avoid obfuscation in minify, but you need to test.

class ClassName {
  getName() {return this.constructor.name;}
};

class ObfuscatedName {
  static name = 'OriginalName';
  
  getName() {return this.constructor.name;}
};

let c = new ClassName();
let o = new ObfuscatedName();

console.log(c.getName());
console.log(o.getName());

Hope this might inspire somebody.

Not the answer you're looking for? Browse other questions tagged or ask your own question.