How to get an Object's Class in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 18 20211 min read

Get an Object's Class in JavaScript #

Use the constructor property on the object to get a reference to the object's class, e.g. obj.constructor. The constructor property returns a reference to the constructor function that created the instance object.

index.js
class Person {} const p1 = new Person(); console.log(p1.constructor); // ๐Ÿ‘‰๏ธ [class Person]

We used the Object.constructor property to get a reference of the class we used to create the object instance.

You can also verify that the constructor property points to the correct class, by using the instanceof operator.

index.js
class Person {} const p1 = new Person(); console.log(p1.constructor); // ๐Ÿ‘‰๏ธ [class Person] console.log(p1 instanceof p1.constructor); // ๐Ÿ‘‰๏ธ true

The instanceof operator checks if the value on the right hand side appears in the prototype of the value on the left hand side.

An alternative approach is to create a method on the class.

index.js
class Person { getClassName() { return this.constructor; } } const p1 = new Person(); console.log(p1.getClassName()); // ๐Ÿ‘‰๏ธ [class Person]

This is a better approach if you need to access the class of the object often. This helps us abstract some of the internals of JavaScript into a method.

Note that all objects (other than ones created using Object.create(null)) have a constructor property.

Objects that are created without a constructor function have a constructor property that points to the main Object constructor for the specific type.

index.js
console.log({}.constructor); // ๐Ÿ‘‰๏ธ [Function: Object] console.log([].constructor); // ๐Ÿ‘‰๏ธ [Function: Array]

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee