Categories
JavaScript Answers

How to get the class name of ES6 class instance with JavaScript?

Spread the love

Sometimes, we want to get the class name of ES6 class instance with JavaScript.

In this article, we’ll look at how to get the class name of ES6 class instance with JavaScript.

How to get the class name of ES6 class instance with JavaScript?

To get the class name of ES6 class instance with JavaScript, we can use the name property of the class or the constructor.name property of the class instance.

For instance, we write

class SomeClass {
  constructor() {}
}

const s = new SomeClass();
console.log(s.constructor.name);
console.log(SomeClass.name);

to create the SomeClass class.

We get the class name of the SomeClass instance s with s.constructor.name.

And we get the name of the class from SomeClass directly with SomeClass.name.

They’ll both log 'SomeClass'.

Conclusion

To get the class name of ES6 class instance with JavaScript, we can use the name property of the class or the constructor.name property of the class instance.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *