Introduction to the definition and difference between the two functions of javascript

Source: Internet
Author: User

Generally, the two call results are the same, but there are still differences.
Method 1:
Copy codeThe Code is as follows:
Function (){
Alert ('Old ');
}
Var B =;
Function (){
B ();
Alert ('new ');
}
A (); // memory overflow occurs in the browser.

Method 2:
Copy codeThe Code is as follows:
Function (){
Alert ('Old ');
}
Var B =;
Var a = function (){
B ();
Alert ('new ');
}
A (); // the browser will generate 'old' and 'new' in order'

Here we can clearly distinguish between the two methods. The order of definition is different.
First, the function a was not re-defined at the beginning and the function itself was executed in it.
In the second way, a = function () is not executed here. Code a in the function has been redefined. So the definition here is valid.
Supplement 1:
Copy codeThe Code is as follows:
Function (){
Alert ('Old ');
}
Var B =;
Function (){
B ();
Alert ('new ');
}

During Compilation: a is first defined as alert ("old") and then B (); alert ("new ");
Runtime: B = function a () {B (); alert ("new") ;}. in this case, B and a are the same, and B is called directly in the function body, both a call and B call results are the same, resulting in stack overflow.
On the other hand
Copy codeThe Code is as follows:
Function (){
Alert ('Old ');
}
Var B =;
Var a = function (){
B ();
Alert ('new ');
}

During Compilation: a is defined as alert ("old ")
Runtime: B = function a () {alert ("old")}; a = function () {B (); alert ("new ")}; at this time, the function body of B does not include any of AB. a only calls B... stack Overflow will not occur in any way...
Supplement 2:
Generally, the first method is used to avoid code pollution, but if you need to retain the original function, you need to use the second method. Both methods comply with w3c.
In fact, the first writing method was only available later, which was 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.