Home > Web Front-end > JS Tutorial > Explanation of the difference between determining whether a function is called new or () in JavaScript_javascript skills

Explanation of the difference between determining whether a function is called new or () in JavaScript_javascript skills

WBOY
Release: 2016-05-16 18:08:17
Original
1597 people have browsed it

Method 1

Copy code The code is as follows:

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
Copy code The code is as follows:

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
Copy code The code is as follows:

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
Copy the code The code is as follows:

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?
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template