function definition mode function A () {} and A=function () {}

Source: Internet
Author: User

In general, the result of the call is the same, but there is a difference.

The first way:

functiona(){    alert(‘old‘);  }var b=a;functiona(){    b();    alert(‘new‘);    }a();//浏览器就会出现内存溢出的情况

The second way:

sequentially
function  a () { Code class= "JS spaces" >     alert ( ' old ' } var  b=a; var  a= function () {      b ();      alert ( ' new ' } a (); //browser will alert out ' old ' and ' new '

The difference between the two ways can be clearly distinguished here. The order of the definitions is different.
The first, in fact, does not redefine a function and executes itself in it.
In the second way, a = function () code A that is not executed in the function is already redefined. So the redefinition here is valid.

Supplement 1:

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

Compile time: First A is defined as alert ("old") and then is defined as B (); Alert ("new");
Runtime: b = function A () {B (); Alert ("New");}, at this point B and a, call B directly in the function body, whether from a or B call results are the same, resulting in a stack overflow

On the other hand

functiona(){    alert(‘old‘);  }var b=a;vara=function(){    b();    alert(‘new‘);}

Compile time: A is defined as alert ("old")
Run Time:

b=functiona(){alert("old")}; a=function(){b();alert("new")};

At this point the function body of B does not include any of the AB, a only call B ... No stack overflow is generated ...

Supplement 2:

In general, you will use the first way to avoid code pollution, but if you need to retain the original function, you have to use the second way of writing, anyway, both methods are consistent.

In fact, the first form of writing is later, and this is optimized.

function definition mode function A () {} and A=function () {}

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.