How to detect if a function is called as constructor ?

The problem is to identify whether the function call is a constructor call or not.
Approach 1:
- Use the instanceof property.
- If the current instance is the instance of a function then this is a constructor call.
- Else, this is a general function call.
Example: This example implements the above approach.
html
<h1 style="color:green;"> zambiatek </h1> <p id="GFG_UP"></p> <button onclick="gfg_Run()"> Click here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to check if the " + "function is called as a constructor<br>" + "Function name - GFG_FUN2"; function GFG_FUN2(val) { var temp = false; if (this instanceof GFG_FUN2 && !this.__previouslyConstructedByVal) { temp = true; this.__previouslyConstructedByVal = true; } return temp; } function gfg_Run() { // Function call var temp = GFG_FUN2(); if (temp == true) { el_down.innerHTML = "Function is called as constructor."; } else { el_down.innerHTML = "Function is not called as constructor."; } } </script> |
Output:
How to detect if a function is called as constructor?
Approach 2:
- Use the .constructor property.
- If this.constructor is equal to the function name then this is a constructor call.
- Else, this is a general function call.
Example: This example illustrates the approach discussed above.
html
<h1 style="color:green;"> zambiatek </h1> <p id="GFG_UP"></p> <button onclick="gfg_Run()"> Click here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to check if the " + "function is called as a constructor<br>" + "Function name - GFG_FUN2"; function GFG_FUN2(val) { var temp = false; if (this.constructor == GFG_FUN2) { temp = true; } if (temp == true) { el_down.innerHTML = "Function is called as constructor."; } else { el_down.innerHTML = "Function is not called as constructor."; } } function gfg_Run() { new GFG_FUN2(); //Call to the function. } </script> |
Output:
How to detect if a function is called as constructor?
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



