ES5 syntax, how JavaScript determines whether a function is new or () called

Source: Internet
Author: User

The ES5 syntax does not support class classes, but you can declare a class by clearing the function as follows:

function person (name) {

This.name=name;

}

var john=new person (' John ');

Console.log (john.name);//john

But this class can be called directly like function execution: person ()

The decision is not to be called by New or () so modify the above class:

function person (name) {

This.name=name;

if (this instanceof person) {

Alert (' New call ');
}else{
Alert (' function call ');
}

}

New person (' Xiaoqiang ')//=> new call

Person (' Xiaoqiang ')//=> function call

Also in the wording can be easily copied and pasted into any class inside the following:

Notation 1:

function person (name) {

This.name=name;

if (this instanceof Arguments.callee) {

Alert (' New call ');
}else{
Alert (' function call ');
}

}

New person (' Xiaoqiang ')//=> new call

Person (' Xiaoqiang ')//=> function call

Notation 2:

function person (name) {

This.name=name;

if (this.constructor = = = Arguments.callee) {

Alert (' New call ');
}else{
Alert (' function call ');
}

}

New person (' Xiaoqiang ')//=> new call

Person (' Xiaoqiang ')//=> function call

It looks like the top three types are perfect, but how to call you will blind you

var jack=new person (' Jack '); =>new Call

Jack.f=person

Jack.f (' Don't believe you try ')//=> new call

ES5 syntax, how JavaScript determines whether a function is new or () called

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.