Function declaration and Expression

Source: Internet
Author: User

Function declaration: directly declare a function fnname () {}; function declaration must have a method name, and the method names that appear in the expression are ignored.

Function expression: points a variable reference to a specified function or anonymous function by assigning a value. For example:

VaR fnname = function () {}; // It can be an anonymous function or a named Function

 

The following two sections of code are analyzed:

<script type="text/javascript">alert(a);function a() {return 'xx';}var a = function a() {return 'x';}alert(a);</script>
<script type="text/javascript">alert(a);function a() {return 'xx';}var a = function a() {return 'x';}alert(a);</script>

 

 

In fact, there is not much difference between the two, mainly in Var A = function a () {}, there is a difference between IE and other browsers, IE, whether it is a function expression or a function declaration, will be mentioned before scope. Why?

<script type="text/javascript">alert(a);var k = function a() {return 'x';}</script>

 

 

Other browsers will prompt a undefined (A is not defined). The rest is just a sequence problem.

 

During pre-resolution, A is function a () {} at this time, regardless of whether it is before or after var.

<script type="text/javascript">alert(a);function a() {return 'xx';}var a = '1';</script>

 

It can be understood that when parsing the <SCRIPT> code segment, the VaR is declared in advance, mentioned before the current scope, and then the function expression is pre-parsed. The definition of VaR A has nothing to do with the position of function A. When var A is executed, the reference of a is changed and it will point to the value "1"

 

 

 

To learn more about the named and anonymous functions, click the following link to view my previous articles:

Hi.baidu.com/meteoric_cry/blog/item/65f8d3c4651d64a58326ac23.html

 

Reprinted please indicate the source :). If you have different opinions, please drop your eggs.

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.