Method 1
function Person(n,a){
this.name = n;
this.age = 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
function Person(n,a){
this.name = n;
this.age = a;
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
function Person(n,a){
this.name = n;
this.age = a;
if(this.constructor === arguments .callee){
alert('new call');
}else{
alert('function call');
}
}
var p = new Person(' jack',30); // --> new call
Person(); // --> function call
seems perfect, but when the function/class is used as There is a problem when calling the method of the own instance object
function Person(n,a){
this.name = n;
this.age = a;
if(this.constructor === arguments.callee){
alert('new call' );
}else{
alert('function call');
}
}
var p = new Person('jack',30); // new object first
p.fn = Person; // Assign the function/class Person to the fn attribute of the own object p
p.fn(); // When calling this sentence, it prompts "This is a new call", which is obviously wrong
Is there a better way?
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn