How to Get a Class Name of an Object in JavaScript

As a JavaScript developer, you may often need to know the class name of an object.

In this Javascript tutorial, we’ll discuss several ways to obtain the class name of an object in JavaScript.

Whether you’re a beginner or an experienced programmer, you’ll find the information in this Javascript tutorial helpful.


Using the constructor property

The simplest way to get the class name of an object is by using the constructor property.

Every object in JavaScript has a constructor property that refers to the function that was used to create the object.

By accessing the name property of the constructor, you can get the class name of the object.

Here’s an example:

class Animal {
  constructor(name) {
    this.name = name;
  }
}

const dog = new Animal('dog');
console.log(dog.constructor.name); // 'Animal'

Using the toString() method

Another way to get the class name of an object is by using the toString() method.

The toString() method returns a string representation of an object.

You can extract the class name from the string representation of the object by using a regular expression.

Here’s an example:

class Animal {
  constructor(name) {
    this.name = name;
  }
}

const dog = new Animal('dog');
console.log(dog.toString().match(/\w+/g)[1]); // 'Animal'

Using Object.prototype.toString.call()

Another way to get the class name of an object is by using Object.prototype.toString.call().

The Object.prototype.toString() method returns a string representation of an object.

By calling it with call(), you can pass in an object as the this value and get its string representation.

You can then extract the class name from the string representation of the object by using a regular expression.

Here’s an example:

class Animal {
  constructor(name) {
    this.name = name;
  }
}

const dog = new Animal('dog');
console.log(Object.prototype.toString.call(dog).match(/\w+/g)[1]); // 'Animal'

Conclusion

In this tutorial, we’ve discussed three ways to get the class name of an object in JavaScript.

Whether you’re a beginner or an experienced programmer, you should now have a good understanding of how to obtain the class name of an object in JavaScript.

Remember to always use the appropriate method based on your needs, as some methods may be more appropriate for certain use cases than others.