How to usethe constructor Property in Javascript

In JavaScript, the constructor property serves as a tag on an object, showing the function that formed it. It’s a means to discover which constructor function was used to craft the object. By using object.constructor, you can simply finds the object’s category without going into complexities, offering a clear path to recognize object types in JavaScript.

Example: In this example we will see how to find the Class Name of an Object using the constructor Property in JavaScript.

Javascript




class Product {
    constructor(name, price) {
        this.name = name;
        this.price = price;
    }
  
    getClassName() {
        return this.constructor.name;
    }
}
  
const product = new Product("Book", 10);
console.log(product.getClassName());


Ouput:

Product

How to get the Class Name of an Object in JavaScript

In this article, we will learn how we can get the class Name of an Object with multiple approaches in JavaScript.

In JavaScript, determining an object’s class name can be done using multiple approaches. The constructor property of an object reveals the function that created it, while the instanceof operator checks if an object is an instance of a class. Additionally, employing Object.prototype.toString() method with the object as an argument helps retrieve its class name in string form. These methods help in identifying the class of an object, help in handling different types of objects within JavaScript programs.

Table of Content

  • Using the constructor Property
  • Using the instanceof Operator

Similar Reads

Approach 1: Using the constructor Property

In JavaScript, the constructor property serves as a tag on an object, showing the function that formed it. It’s a means to discover which constructor function was used to craft the object. By using object.constructor, you can simply finds the object’s category without going into complexities, offering a clear path to recognize object types in JavaScript....

Approach 2: Using the instanceof Operator

...