Get the Class Name of an Object in JavaScript
To retrieve the class name of an object, access the name
property on the object’s constructor, e.g. obj.constructor.name
. The constructor
property returns a reference to the Object constructor function that created the instance object.
Example –
class Person {}
const thePerson = new Person();
console.log(thePerson.constructor.name);
In this example. we accessed the name
property of Object.constructor
The Object.constructor
property refers to the constructor function that created the object.
You can also create a method on the class that returns the class name of the object.
Example –
class Person {}
const thePerson = new Person();
console.log(thePerson.constructor);
The code defines a class called Person()
and creates a new instance of that class called thePerson
. It then prints out the name of the class that thePerson
belongs to.
class Person {
getClassName() {
return this.constructor.name;
}
}
const thePerson = new Person();
const className = thePerson.getClassName();
console.log(className);
If you need to access the Object.constructor.name property frequently, consider creating a method to make it more accessible.
Note: All objects have a constructor property, except for those created using Object.create(null)
.
console.log({}.constructor.name);
console.log([].constructor.name);
The code above is logging the constructor name of an empty object and an empty array to the console. The constructor name is a property of an object that returns the function that created the object. In this case, the empty object is created by the Object constructor function and the empty array is created by the Array constructor function.
Every object has a constructor property that points to the main Object constructor for the specific type.