You can get it from name
on constructor
:
console.log(object.constructor.name);
When you do ex = new Example
, for instance, in the normal course of things that makes Example.prototype
the prototype of the object that was created (ex
), and the object inherits a constructor
property from that object that refers back to the constructor (Example
).
I say "in the normal course of things" because there are various ways those normal relationships can be changed. For instance, code could have overridden the constructor
property with an own property on the object (ex.constructor = somethingElse;
). To rule out that specific scenario, you could use:
console.log(Object.getPrototypeOf(object).constructor.name);
Live example:
class Example1 {
}
const e1 = new Example1();
console.log(e1.constructor.name); // "Example1"
class Example2 {
constructor() {
this.constructor = "I'm special";
}
}
const e2 = new Example2();
console.log(Object.getPrototypeOf(e2).constructor.name); // "Example2"
The TC39 committee members that specify JavaScript were happy enough to use the instance's constructor
property in Promise
s when building the new promise that then
and catch
return (see Step 3 here which goes here and reads constructor
from the instance) (and in some other places), so you wouldn't be out on your own if you also used it. They don't even go to the prototype of the instance.
But yes, just for completeness, even if you go to the prototype for it, it's still possible for that to lead you astray, since the prototype's constructor
property can also be mucked with:
class Example {
}
Example.prototype.constructor = Object; // Why would anyone do this? People are weird.
const e = new Example();
console.log(Object.getPrototypeOf(e).constructor.name); // "Object"
It's also possible to redefine the name
on a function:
class Example {
}
// Why would someone do this? People are weird.
Object.defineProperty(Example, "name", {
value: "flibberdeegibbit"
});
const e = new Example();
console.log(Object.getPrototypeOf(e).constructor.name); // "flibberdeegibbit"
So...caveat user.
Note that the function name
property is new as of ES2015 (as is class
syntax). If you're using class
syntax via a transpiler, it may or may not set name
correctly.