How to use Constructor Property In Javascript

Each JavaScript object has a constructor property which refers to the constructor function that created it. By comparing the constructor property of an object with a specific constructor function, you can identify the type of the object. This method provides a direct way to check the constructor function of an object and can be useful in certain scenarios.

Syntax:

if (object.constructor === DerivedClass) {
// Process object as DerivedClass
}

Example: The below example will explain the use of constructor property tonarrow a type of derived class.

Javascript




interface Shape {
    draw(): void;
}
 
class Circle implements Shape {
    draw() {
        console.log("Drawing a circle");
    }
}
 
class Rectangle implements Shape {
    draw() {
        console.log("Drawing a rectangle");
    }
}
 
const shapes: Shape[] =
    [new Circle(), new Rectangle(), new Circle()];
 
for (const shape of shapes) {
    if (shape.constructor === Circle) {
        console.log("Circle instance found");
        (shape as Circle).draw();
    }
    else if (shape.constructor === Rectangle) {
        console.log("Rectangle instance found");
        (shape as Rectangle).draw();
    }
}


Output:

Circle instance found
Drawing a circle
Rectangle instance found
Drawing a rectangle
Circle instance found
Drawing a circle


How to Narrow a Type of Derived Class Instances while Processing an Array ?

When it comes to JavaScript arrays that contain derived class instances, narrowing down the types is a must to access the specific functions or properties that are unique to those derived classes. Narrowing encompasses an act of specifically type-checking and casting objects explicitly to their derived types.

Table of Content

  • Using instanceof Operator
  • Using Constructor Property

Similar Reads

Using instanceof Operator

The instanceof operator checks if an object is an instance of a particular class or its prototype chain. It’s commonly used to determine the type of an object in JavaScript. This approach is straightforward and widely used, especially when dealing with inheritance hierarchies....

Using Constructor Property

...

Contact Us