While JavaScript is not strictly typed like languages such as C# or Java, it does still have class support. Originally, working with classes was mostly done through “constructor” functions and methods added to the prototype of that function which allowed you to use a JavaScript class similar to how you would in object-oriented programming languages. With ES6, you are now able to define classes in a more familiar syntax even though the underlying structure still functions as it did before.
The more you use classes, the more likely you will need to access meta data about a given class. So, how do you get a class’s name in JavaScript?
yourObject.constructor.name
Class.name
What’s the difference? Here is an example:
As you can see above, both solutions are similar but there is an important distinction. The name
property is undefined
once the class is instantiated so you will need to use Blog.constructor.name
if you are trying to get the class name of an object. If you only want a string representation of a class’s name, and you have the class, just use Blog.name
. Something important to keep in mind is that if you decide to add a static name
property or get
method to your class, you will effectively replace the original name of that class:
Other than that, the process of getting a class’s name in JavaScript is pretty simple despite not being completely straightforward. Enjoy!