Advertisements
How to Get the Class Name of an Object in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the name
Property
You can use the name
property of the object's constructor function to get the name of the class that is used to instantiated the object. Let's take a look an example:
Example
Try this code »<script>
class Rectangle {
// Class constructor
constructor(length, width) {
this.length = length;
this.width = width;
}
// Class method
getArea() {
return this.length * this.width;
}
}
var rectObj = new Rectangle(5, 10);
alert(rectObj.getArea()); // Outputs: 50
alert(rectObj.constructor.name) // Outputs: Rectangle
</script>
Please check out the tutorial on JavaScript ES6 features to learn more about JavaScript classes.
Related FAQ
Here are some more FAQ related to this topic:
- How to remove a property from a JavaScript object
- How to get day, month and year from a date object in JavaScript
- How to dynamically access object property using variable in JavaScript
Advertisements