/

JavaScript: How to Get the Class Name of an Object

JavaScript: How to Get the Class Name of an Object

If you have an object that is generated from a class and you want to retrieve its class name, there are a couple of ways you can do so. Let’s explore these techniques.

Suppose you have an object that is generated from a class called Dog. You want to get the class name of this object.

Here’s an example code snippet:

1
2
3
4
5
class Dog {
// Class implementation
}

const roger = new Dog();

In this case, roger is the object that is created from the Dog class. But how can you obtain the class name of this object if you don’t know it?

One approach is to access the object’s constructor and then reference its name property. Here’s how you can do it:

1
2
3
4
5
6
7
class Dog {
// Class implementation
}

const roger = new Dog();

console.log(roger.constructor.name); // Output: 'Dog'

The above code snippet will log the class name (‘Dog’) to the console. This name property represents the class name associated with the object.

Another way to check the class name is by directly comparing the constructor property of the object to the class. Here’s an example:

1
2
3
4
5
6
7
class Dog {
// Class implementation
}

const roger = new Dog();

roger.constructor === Dog; // Output: true

In this case, the comparison roger.constructor === Dog evaluates to true if roger is an instance of the Dog class.

Knowing how to get the class name of an object can be useful in various scenarios, especially when you need to perform certain actions based on the object’s class.

Tags: JavaScript, object, class, class name