1. Basic concepts: the way functions are defined

There are two ways to define a function:

  1. Declaration of functions
  2. Functional expression

1.1 Declaration of functions

The following method add is the code structure of the function declaration:

functionAdd (x,y){alert(x+y)} add(1,2) // popup displays: 3Copy the code

One of the most important features of function declaration is function declaration promotion, which means that the function declaration is read before the code is executed. This means that the function declaration can be placed after the statement that calls it. The following code executes correctly:

Add (1, 2); // The pop-up window displays: 3function add(x,y){  
    alert(x+y) 
}  
Copy the code

1.2 Function Expression

There are several different syntax for functional expressions. The most common and representative one is as follows:

var add = function(x,y){alert(x+y)} add(1,2) // popup: 3Copy the code

This form looks like a regular variable assignment statement. The difference between a function expression and a function declaration, however, is that the function expression must be assigned before it can be used. So this code will execute in error:

Add (1,2) // no popup, error: add is not afunction  
var add = function(x,y){  
    alert(x+y)  
} 
Copy the code

This happens because when the parser loads data into the execution environment, the parser reads the function declaration first and makes it available before any code is executed. In the case of functional expressions, they are not actually parsed until the parser reaches the line of code on which they reside. Functions created in function expressions are called anonymous functions because there is no identifier after the function keyword.

2. Call method of anonymous function

Anonymous functions, as the name implies, have no name. The above creation of a function expression actually creates an anonymous function and assigns the value of the anonymous function to the variable add, which is called by adding a pair of parentheses () after the variable add, or add(1,2) if any arguments are passed in. This is one way to call an anonymous function.

Another way to call an anonymous function is by enclosing the anonymous function with () followed by a pair of parentheses (containing the argument list). Let’s look at the following example:

alert((function(x,y){returnx+y; })(2,3)) // alert((new Function()"x"."y"."return x+y")(2,3)) // popup displays 5Copy the code

In javascript, there is no such thing as block-level scope. The way this code mimics block-level scope (usually called private scope) is expressed in the following syntax:

(function(){// here is the block-level scope})();Copy the code

The above code defines and immediately calls an anonymous function. The function declaration is enclosed in a pair of parentheses to indicate that it is actually a function expression. This function is immediately called by another pair of parentheses immediately following it. A note of caution, however:

function() {} ();Copy the code

The above code is wrong because Javascript uses the function keyword as the start of a function declaration, and function declarations cannot be followed by parentheses. If you do not display this to the compiler, it will default to a missing function and throw a syntax error. Because the function declaration needs a name. Interestingly, even if you add a name to the wrong code above, it will give you a syntax error, but for a different reason. Uncaught SyntaxError: Unexpected Token (.

Enclosing parentheses () after an expression will execute immediately, but enclosing parentheses () after a statement means something completely different, just grouping operators.

function foo(){
   alert('Test popover'}() // SyntaxError: Unexpected Token) // Error because grouping operators need to include expressionsfunction foo(){ 
    alert('Test popover'}(1) // (1) => equivalent to 1 // equivalent to foo (1)Copy the code

So if the code above wants to get the popover prompt it wants, it must implement the assignment, such as

a = function(){
    alert('Test popover'}() // Popup prompts successCopy the code

The “A =” fragment tells the compiler that this is a function expression, not a function declaration. Because function expressions can be followed by parentheses.

So the following two pieces of code are equivalent

var aa = function(x){alert(x)}(5) // Popup displays: 5Copy the code
(function(x){alert(x)})(5) // Pop-up window display: 5Copy the code

From the above understanding of functions and anonymous functions, we derive a concept, that is, self-executing functions. So why does a =function(){}() make the compiler think this is a function expression instead of a function declaration?

3. Execute anonymous functions automatically

Self-executing functions are defined and called together. We create an anonymous function and execute it immediately. Since external variables cannot reference it, it is released soon after execution. Crucially, this mechanism does not pollute global objects.

Let’s look at some of the more interesting expressions of self-executing functions:

// The following two parentheses () are executed immediately (function() {/* code */} ())function() {/* code */})() {/* code */})() {/* code */})() {/* code */})() {/* code */})() Everything else defaults to an expression var I =function () { return 10; } ();  
true && function () { /* code */ } ();  
0, function() { /* code */ } (); If you don't care about the return value, or are not afraid of being difficult to read // you can even use thefunctionAdd unary operation symbol in front!function () { /* code */ } ();  
~function () { /* code */ } ();  
-function () { /* code */ } ();  
+function() { /* code */ } (); / / there is a case, use the new keyword, you can also use, but I'm not sure its new efficiency / / http://twitter.com/kuvos/status/18209252090847232function () { /* code */ }  
new function() {/* code */} () {/* code */} ()Copy the code

4. To summarize

I believe that you have a new understanding of the function, I hope to help you.

If there is wrong or need to improve or have a different introduction welcome to reply to discuss. 😛

📖 Reference link

  • www.cnblogs.com/TomXu/archi…
  • www.cnblogs.com/mzwr1982/ar…
  • www.ruanyifeng.com/blog/2009/0…
  • Blog.csdn.net/natineprinc…