JavaScript 如何检测函数是否被调用为构造函数
问题是要确定函数调用是否是构造函数调用。
方法1
- 使用 instanceof 属性 。
- 如果当前实例是函数的实例,那么这是一个构造函数调用。
- 否则,这是一个普通的函数调用。
示例: 这个示例实现了上述方法。
<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>
HTML
输出:
方法2
- 使用 . 构造器属性 .
- 如果 this.constructor 等于函数名,则为构造函数调用。
- 否则,为普通函数调用。
示例: 这个示例演示了上面讨论的方法。
<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>
HTML
输出: