SoFunction
Updated on 2025-03-01

Explanation of the difference between determining whether a function is new or called in JavaScript

Method 1
Copy the codeThe code is as follows:

function Person(n,a){
= n;
= a;
if(this instanceof Person){
alert('new call');
}else{
alert('function call');
}
}
var p = new Person('jack',30); // --> new call
Person(); // --> Function Call

Method 2
Copy the codeThe code is as follows:

function Person(n,a){
= n;
= a;
if(this instanceof ){
alert('new call');
}else{
alert('function call');
}
}
var p = new Person('jack',30); // --> new call
Person(); // --> Function Call

Method 3
Copy the codeThe code is as follows:

function Person(n,a){
= n;
= a;
if( === ){
alert('new call');
}else{
alert('function call');
}
}
var p = new Person('jack',30); // --> new call
Person(); // --> Function Call

It seems perfect, but when calling a function/class as a method of its own instance object, it will be a problem
Copy the codeThe code is as follows:

function Person(n,a){
= n;
= a;
if( === ){
alert('new call');
}else{
alert('function call');
}
}
var p = new Person('jack',30); // New object first
= Person; // Assign function/class Person to the fn attribute of its own object p
(); // This sentence prompts "This is a new call", which is obviously wrong

Is there a better way?