Method 1
Copy codeThe Code is as follows:
Function Person (n, ){
This. name = n;
This. age =;
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 codeThe Code is as follows:
Function Person (n, ){
This. name = n;
This. age =;
If (this instanceof arguments. callee ){
Alert ('new call ');
} Else {
Alert ('function call ');
}
}
Var p = new Person ('jack', 30); // --> new call
Person (); // --> function call
Method 3
Copy codeThe Code is as follows:
Function Person (n, ){
This. name = n;
This. age =;
If (this. constructor === arguments. callee ){
Alert ('new call ');
} Else {
Alert ('function call ');
}
}
Var p = new Person ('jack', 30); // --> new call
Person (); // --> function call
It seems perfect, but when the function/class is used as the method of its own instance object, the call goes wrong.
Copy codeThe Code is as follows:
Function Person (n, ){
This. name = n;
This. age =;
If (this. constructor === arguments. callee ){
Alert ('new call ');
} Else {
Alert ('function call ');
}
}
Var p = new Person ('jack', 30); // a new object is first created.
P. fn = Person; // assign the function/class Person to the fn attribute of the p object.
P. fn (); // The system prompts "this is a new call" when calling this sentence. This is obviously incorrect.
Is there a better way?