Question

This question must be rather simple indeed, but I cannot google or duckduckgo the answer, probably because 99% of beginner tutorials involve creating a Person object with a name property (which is unrelated to the constructor.name but pollutes the search results).

Instances of Object Objects can be detected using instance.constructor.name:

var foo = new Object;
foo.constructor.name; // "Object"

How do I set the constructor name on my own objects?

var Bar = function(){};
var baz = new Bar;
baz.constructor.name // "" <- Empty string
Était-ce utile?

La solution

Instead of defining your constructor as a variable Bar that is set to an anonymous function, you can either do this:

function Bar() {}

Or this:

var Bar = function ConstructorNameHere() {};

Where the ConstructorNameHere name can actually be Bar again:

var Bar = function Bar() {};

(That should work in Chrome and FF, not sure but not very hopeful about IE.)

Autres conseils

Important warning:

If you use a JS minifier then the name will be likely optimized away and suddenly constructor.name becomes n instead of the object name you were expecting.

This can be especially hard to debug if it's only enabled in production.

I wanted to make an answer to consolidate things from answers and comments above.

The most deterministic way to have the class name work (especially after minification) is to set a name property on the class itself. All of the following are equivalent:

// option 1
function MyClass() {}
MyClass.name = 'MyClass'

// option 2
class MyClass {}
MyClass.name = 'MyClass'

// option 3 (preferred)
class MyClass {
  static name = 'MyClass'
}

If you want the class name to be dynamic, you create a factory:

function classFactory(className) {
    return class {
        static name = className;
    }
}

const MyClass = classFactory('MyClass')
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top