Introduction to the definition of JavaScript two function and its difference description _javascript skills

Source: Internet
Author: User
In general, the results of the two calls are the same, but there is a difference.
The first way:
Copy Code code as follows:

function A () {
Alert (' old ');
}
var b=a;
function A () {
b ();
Alert (' new ');
}
A ();//The browser will have a memory overflow situation

The second way:
Copy Code code as follows:

function A () {
Alert (' old ');
}
var b=a;
var a=function () {
b ();
Alert (' new ');
}
A ();//The browser will alert the ' old ' and ' new ' in order

Here it is clear to distinguish between the two ways. The order of the definitions is different.
The first, in fact, did not redefine the function of a at first and executed itself in it.
The second way, a = function () The code a that has not been executed into the function is redefined. So the redefinition here is valid.
Add 1:
Copy Code code as follows:

function A () {
Alert (' old ');
}
var b=a;
function A () {
b ();
Alert (' new ');
}

At compile time: first A is defined as alert ("old"), which is then defined as B (), Alert ("new");
Runtime: b = function A () {B (); Alert ("New");}, at this time B and a, call B directly in the function body, regardless of whether the result is called from A or B, resulting in a stack overflow
On the other hand
Copy Code code as follows:

function A () {
Alert (' old ');
}
var b=a;
var a=function () {
b ();
Alert (' new ');
}

Compile time: A is defined as alert ("old")
Runtime: B=function A () {alert ("old")}; A=function () {b (); Alert ("New")}; At this point, the function body of B does not include any of the AB, and a only calls B ... No stack overflow is generated ...
Add 2:
In general, the first method will be used to avoid code pollution, but if you need to retain the original function, it is necessary to use the second way, anyway, both methods are consistent with the consortium.
In fact, the first form of writing is later, and this formulation is optimized.
Related Article

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.