Differences in function definitions in JavaScript

Source: Internet
Author: User
[Javascript] try {fun1 ();} catch (e) {alert (e) ;}; try {fun2 ();} catch (e) {alert (e) ;}; functionfun1 () {alert (& quot; thisfun1. & quot;) ;} varfun2function () {alert (& quot; thisisf

[Javascript]
Try {
Fun1 ();
} Catch (e ){
Alert (e );
};
 
Try {
Fun2 ();
} Catch (e ){
Alert (e );
};
 
Function fun1 (){
Alert ("this is fun1 .");
}
 
Var fun2 = function (){
Alert ("this is fun2 .");
}
 
Try {
Fun2 ();
} Catch (e ){
Alert (e );
};
Try {
Fun1 ();
} Catch (e ){
Alert (e );
};

Try {
Fun2 ();
} Catch (e ){
Alert (e );
};

Function fun1 (){
Alert ("this is fun1 .");
}

Var fun2 = function (){
Alert ("this is fun2 .");
}

Try {
Fun2 ();
} Catch (e ){
Alert (e );
};
This is because it is more helpful to distinguish between the definition of a function and the definition of a general variable.

 


However,

[Javascript]
Function fun1 (){
Alert ("this is fun1 .");
}
Function fun1 (){
Alert ("this is fun1 .");
}


When the function statement is parsed, it will be upgraded. )

This means that the function defined by this method will be moved to the top level of the scope at the time of definition.

That is to say, this function can be called within the defined scope, which does not conform to the concept of "first defining and then calling.

This will affect the readability of the code and cause some confusion. Therefore, you should pay attention to "define and then call" During encoding ".

 


The following code solves the problems mentioned above.

[Javascript]
Var fun2 = function (){
Alert ("this is fun2 .");
}
Var fun2 = function (){
Alert ("this is fun2 .");
}


Function fun2 must be called after the function is defined, or an error will be thrown.

This syntax is similar to defining a variable. fun2 does not exist before defining fun2.

Although this method solves the problem of not complying with "first definition and then call", it is not intuitive enough.

Excerpt from jian sheng's code Memorandum
 

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.