The difference between the JS function expression and the function declaration

Source: Internet
Author: User

We already know that adding wrapper functions outside of arbitrary code fragments can "hide" internal variables and function definitions, and external scopes cannot access any content inside the wrapper function.

For example:

var a = 2;function foo () {//<--Add this line var a = 3;console.log (a);//3}//<--and this line foo (); <--and this line Console.log (a); 2

While this technique can solve some problems, it is not ideal because it leads to some additional problems. First, a named function foo () must be declared, meaning that the name Foo itself "pollutes" the scope (in this case, the global scope). Second, you must explicitly call this function through the function name (foo ()) to run the code in it.

This is ideal if the function does not require a function name (or at least the function name can be used without contaminating the scope) and is able to run automatically.

Fortunately, JavaScript provides a solution to both of these problems,

var a = 2; (function foo () {///<--Add this line var a = 3;console.log (a);//3}) (); <--and this line Console.log (a); 2

Next we describe what happened here.

First, the declaration of the wrapper function is to (function ... And not just with the function ... Begin. While it seems that this is not a very conspicuous detail, it is actually a very important distinction. Functions are treated as function expressions rather than as a standard function declaration. The simplest way to differentiate a function declaration from an expression is to see where the function keyword appears in the declaration (not just one line of code, but the position in the entire declaration). If the function is the first word in the declaration, then it is a functional declaration, otherwise it is a function expression.

The most important difference between a function declaration and a function expression is where their name identifiers will be bound. Compare the previous two code snippets. In the first fragment, Foo is bound to the scope and can be called directly from Foo (). In the second fragment, Foo is bound to a function in the function expression itself rather than in the scope. In other words, (function foo () {.}) as a functional expression means that Foo can only be in the. The location represented is accessed, and the outer scope is not. The foo variable name is hidden in itself, meaning that the external scope is not unnecessarily polluted.

The following part of the original source: http://www.cnblogs.com/isaboy/p/javascript_function.html

Javascript function is ubiquitous and powerful! JavaScript functions allow JS to have some object-oriented features, such as encapsulation, inheritance, and so on, can also be used to reuse code. But there are two sides to things, JavaScript functions sometimes more "wayward", if you do not understand its "temperament", it is likely to give you to create some unexpected trouble (bugs) out.

There are two types of Javascript function:

1) function declaration (functions Declaration);

    function declaration functions    fundeclaration (type) {        return type=== "Declaration";    }

2) function expression.

    function Expression    var funexpression = function (type) {        return type=== "expression";    }

The code above looks very similar and doesn't feel much different. But in fact, a "trap" on JavaScript functions is embodied in JavaScript two types of function definitions. Here's a look at two pieces of code (labeled Code 1 and Code 2, respectively):

1     fundeclaration ("Declaration");//=> true2     function fundeclaration (type) {3         return type=== " Declaration "; 4     }
1     funexpression ("Expression");//=>error2     var funexpression = function (type) {3         return type=== " Expression "; 4     }
A function that is created with a function declaration can be called before the fundeclaration is defined, whereas a funexpression function created with a function expression cannot be called before the funexpression is assigned a value. fundeclaration
Why is this so?! This is to understand the difference between JavaScript function two types: functions created with function declarations can be called after function parsing (such as parsing), and functions created with function expressions are assigned at run time and are not invoked until the expression is assigned.


The code 1 Segment JS function is equivalent to:
    function Fundeclaration (type) {        return type=== "Declaration";    }    Fundeclaration ("Declaration");//=> True
The code 2 Segment JS function is equivalent to:
    var funexpression;    Funexpression ("expression");//==>error    funexpression = function (type) {        return type=== "expression";    }

At run time, the code above defines only the funexpression variable, but the value is undefined. Therefore, you cannot make a function call on undefined. At this point the Funexpression assignment statement has not been executed. To further deepen the difference between the two types of JS functions, here is a more confusing example, see the following code (code snippet 4):

1     var SayHello; 2     Console.log (typeof (Sayhey));//=>function     3     console.log (typeof (Sayho));//= >undefined 4     if (true) {5         function Sayhey () {6             console.log ("Sayhey"); 7         } 8         SayHello = function s Ayho () {9             console.log ("SayHello"),     }11     } else {         function sayhey () {             Console.log (" SayHey2 "),         }15         SayHello = function Sayho () {             console.log (" SayHello2 ");     Sayhey ();//= SayHey2     sayHello ();//= = SayHello

Analysis: Sayhey is created with a function declaration, the JS compiler in the JS parsing function definition of function promotion, that is, in parsing the JS code, JS compiler (conditional judgment does not form a new scope, Two Sayhey function definitions are promoted beyond the conditional judgment) detects that there are two sayhey definitions with the same name in the scope, the first one is promoted first, the second definition is then promoted (the second definition is under the first definition), and the second definition overrides the first sayhey definition, So Sayhey () output SayHey2, and SayHello is created with a function expression, the content of its expression is in the JS runtime (not parsing) to determine (here the condition is played), so the SayHello expression executes the first function definition and assign a value, The SayHello () output SayHello.

Code Snippet 4 is actually equivalent to the following code (code snippet 5):

1     var SayHello; 2     function Sayhey () {3             console.log ("Sayhey"); 4         } 5     function Sayhey () {6             Console.log ("SayHey2"); 7     } 8     Console.log (typeof (Sayhey));//=>function     9     console.log (typeof (Sayho));//=> UNDEFINED10     if (true) {One         //hoisting ...         SayHello = function Sayho () {             console.log ("SayHello"), +     }15     } else {         //hoisting ...         SayHello = function Sayho () {             console.log ("SayHello2"),         }20     }     Sayhey ();//= > SayHey2     sayHello ();//= SayHello

Some people may suspect that the definition of function Sayhey is the second one covering the first one? We can output the source code of Sayhey, there is a picture of the truth, as shown in:

Summarize

There is a difference between function declarations and function expressions in Javascript, function declarations are promoted in JS parsing, so in the same scope, the function can be called regardless of where the function declaration is defined. The value of the function expression is determined at the JS runtime and is called after the expression assignment is complete. This tiny difference may lead to unexpected bugs in the JS code, which can cause you to fall into an inexplicable trap.

Finally, we enclose the core steps of the two functions of SayHello and Sayhey in code Snippet 4 (Personal understanding, if there are objections welcome message discussion):

The main steps to perform for the SayHello function.

The difference between the JS function expression and the function declaration

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.