How to detect if a function is called as constructor ?
Last Updated :
23 Jan, 2023
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;" >
GeeksforGeeks
</ 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;" >
GeeksforGeeks
</ 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?
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...