An anonymous function that executes immediately

 

;(function() {})();

1. He is called an anonymous function that runs immediately (also called an immediate call function)

2. When an anonymous function is enclosed and then followed by a parenthesis, the anonymous function can run immediately! There is wood and it is amazing~ 

3. To use a function, we must first declare its existence. The most common way we use is to use the function statement to define a function

4. Function object 
 The Function object is an inherent object in JavaScript, and all functions are actually a Function object.

  Let's see first, can the Function object directly use the constructor to create a new function? The answer is yes.

  

var abc = new Function("x","y","return x*y;");
alert(abc(2,3)); // "6"

5. Anonymous functions do not have names, so it extends to the question of how should we call them (O_O)?

      Anonymous function call ①

     

var abc=function(x,y){
return x+y;
}
alert(abc(2,3)); // "5"

  The above operation is actually equivalent to defining functions in a different way. This usage is what we encounter more frequently.

  For example, when we set an event handler for a DOM element, we usually do not name them, but assign an anonymous function to their corresponding event reference. 

    Anonymous function call ②

  Use () to enclose an anonymous function, followed by a pair of parentheses (containing the parameter list).

  

alert((new Function("x","y","return x*y;"))(2,3));// "6"

6. What is the role of parentheses?

Parentheses can combine our expressions into blocks, and each block, that is, each pair of parentheses, has a return value. This return value is actually the return value of the expression in parentheses.

Therefore, when we enclose an anonymous function with a pair of parentheses, what the parentheses actually return is the Function object of an anonymous function.

Therefore, a pair of parentheses plus an anonymous function gets us its reference position just like a function with a name. So if you add a parameter list after this reference variable, you will achieve the normal function call form. 

7. Function declaration, function expression, anonymous function

Function declaration: function fnName () {…}; Use the function keyword to declare a function, and then specify a function name, which is called function declaration.

Function expression var fnName = function () {…}; Use the function keyword to declare a function, but do not name the function, and finally assign the anonymous function to a variable, called a function expression, which is the most common function expression syntax form .

Anonymous function: function () {}; Use the function keyword to declare a function, but do not name the function, so it is called an anonymous function. Anonymous functions belong to function expressions. Anonymous functions have many functions. Assign a variable to create a function, and assign a Events become event handlers or create closures, etc.

The difference between a function declaration and a function expression is that

1. When the Javascript engine parses the javascript code, it will 'Function declaration Hoisting' (Function declaration Hoisting) the function declaration on the current execution environment (scope), and the function expression must wait until the Javascirtp engine executes to its line before it will start from the parses function expressions line by line from top to bottom

2. The function can be called immediately by adding parentheses after the function expression, but not in the function declaration. It can only be called in the form of fnName().

Chestnut①

copy code
fnName();
function fnName(){
    ...
}
// OK, since function declarations are 'hoisted', function calls can be preceded by function declarations

fnName();
var fnName=function(){
    ...
}
//Error, the variable fnName has not yet saved a reference to the function, the function call must be after the function expression
copy code

Chestnut ②

copy code
var fnName=function(){
    alert('Hello World');
}();
//Add parentheses after the function expression, when the javascript engine parses here, the function can be called immediately
function fnName(){
    alert('Hello World');
}();
//No error will be reported, but the javascript engine only parses the function declaration, ignoring the following parentheses, the function declaration will not be called
function(){
    console.log('Hello World');    
}();
//Syntax error, although the anonymous function is a function expression, the assignment operation is not performed,
//So the javascript engine treats the function keyword at the beginning as a function declaration, and reports an error: a function name is required
copy code

To call it immediately after adding parentheses after the function body, the function must be a function expression, not a function declaration.

Chestnut ③

copy code
(function(a){
    console.log(a); //firebug outputs 123, using the () operator
})(123);

(function(a){
    console.log(a); //firebug outputs 1234, using the () operator
}(1234));

!function(a){
    console.log(a); //firebug outputs 12345, use! operator
}(12345);

+function(a){
    console.log(a); //firebug outputs 123456, using the + operator
}(123456);

-function(a){
    console.log(a); //firebug outputs 1234567, using the - operator
}(1234567);

var fn=function(a){
    console.log(a); //firebug outputs 12345678, using the = operator
}(12345678)
copy code

 

You can see the output result, add it in front of function! , +, - and even commas can have the effect of being executed immediately after the function is defined, while (), ! , +, -, = and other operators convert function declarations into function expressions, eliminating the ambiguity between the javascript engine identifying function expressions and function declarations, and telling the javascript engine that this is a function expression, not a function declaration, which can be found in Put parentheses after it and execute the code of the function immediately.

Parentheses are the safest thing to do because ! , +, - and other operators will also operate with the return value of the function, sometimes causing unnecessary trouble.

But what's the use of writing this way?

The concept of private scope is not used in javascript. If you declare some variables in the global or local scope on a project developed by multiple people, they may be accidentally overwritten by others with variables of the same name. According to the javascript function The characteristics of the scope chain, you can use this technique to imitate a private scope, use an anonymous function as a "container", the "container" can access external variables, and the external environment cannot access the variables inside the "container", so ( function(){…} )() Internally defined variables will not conflict with external variables, commonly known as "anonymous wrapper" or "namespace".

JQuery uses this method, wrapping the JQuery code in ( function (window,undefined){...jquery code...} (window), when calling the JQuery code in the global scope, it can protect the internal variables of JQuery.

 
 

 

;(function() {})();

1. He is called an anonymous function that runs immediately (also called an immediate call function)

2. When an anonymous function is enclosed and then followed by a parenthesis, the anonymous function can run immediately! There is wood and it is amazing~ 

3. To use a function, we must first declare its existence. The most common way we use is to use the function statement to define a function

4. Function object 
 The Function object is an inherent object in JavaScript, and all functions are actually a Function object.

  Let's see first, can the Function object directly use the constructor to create a new function? The answer is yes.

  

var abc = new Function("x","y","return x*y;");
alert(abc(2,3)); // "6"

5. Anonymous functions do not have names, so it extends to the question of how should we call them (O_O)?

      Anonymous function call ①

     

var abc=function(x,y){
return x+y;
}
alert(abc(2,3)); // "5"

  The above operation is actually equivalent to defining functions in a different way. This usage is what we encounter more frequently.

  For example, when we set an event handler for a DOM element, we usually do not name them, but assign an anonymous function to their corresponding event reference. 

    Anonymous function call ②

  Use () to enclose an anonymous function, followed by a pair of parentheses (containing the parameter list).

  

alert((new Function("x","y","return x*y;"))(2,3));// "6"

6. What is the role of parentheses?

Parentheses can combine our expressions into blocks, and each block, that is, each pair of parentheses, has a return value. This return value is actually the return value of the expression in parentheses.

Therefore, when we enclose an anonymous function with a pair of parentheses, what the parentheses actually return is the Function object of an anonymous function.

Therefore, a pair of parentheses plus an anonymous function gets us its reference position just like a function with a name. So if you add a parameter list after this reference variable, you will achieve the normal function call form. 

7. Function declaration, function expression, anonymous function

Function declaration: function fnName () {…}; Use the function keyword to declare a function, and then specify a function name, which is called function declaration.

Function expression var fnName = function () {…}; Use the function keyword to declare a function, but do not name the function, and finally assign the anonymous function to a variable, called a function expression, which is the most common function expression syntax form .

Anonymous function: function () {}; Use the function keyword to declare a function, but do not name the function, so it is called an anonymous function. Anonymous functions belong to function expressions. Anonymous functions have many functions. Assign a variable to create a function, and assign a Events become event handlers or create closures, etc.

The difference between a function declaration and a function expression is that

1. When the Javascript engine parses the javascript code, it will 'Function declaration Hoisting' (Function declaration Hoisting) the function declaration on the current execution environment (scope), and the function expression must wait until the Javascirtp engine executes to its line before it will start from the parses function expressions line by line from top to bottom

2. The function can be called immediately by adding parentheses after the function expression, but not in the function declaration. It can only be called in the form of fnName().

Chestnut①

copy code
fnName();
function fnName(){
    ...
}
// OK, since function declarations are 'hoisted', function calls can be preceded by function declarations

fnName();
var fnName=function(){
    ...
}
//Error, the variable fnName has not yet saved a reference to the function, the function call must be after the function expression
copy code

Chestnut ②

copy code
var fnName=function(){
    alert('Hello World');
}();
//Add parentheses after the function expression, when the javascript engine parses here, the function can be called immediately
function fnName(){
    alert('Hello World');
}();
//No error will be reported, but the javascript engine only parses the function declaration, ignoring the following parentheses, the function declaration will not be called
function(){
    console.log('Hello World');    
}();
//Syntax error, although the anonymous function is a function expression, the assignment operation is not performed,
//So the javascript engine treats the function keyword at the beginning as a function declaration, and reports an error: a function name is required
copy code

To call it immediately after adding parentheses after the function body, the function must be a function expression, not a function declaration.

Chestnut ③

copy code
(function(a){
    console.log(a); //firebug outputs 123, using the () operator
})(123);

(function(a){
    console.log(a); //firebug outputs 1234, using the () operator
}(1234));

!function(a){
    console.log(a); //firebug outputs 12345, use! operator
}(12345);

+function(a){
    console.log(a); //firebug outputs 123456, using the + operator
}(123456);

-function(a){
    console.log(a); //firebug outputs 1234567, using the - operator
}(1234567);

var fn=function(a){
    console.log(a); //firebug outputs 12345678, using the = operator
}(12345678)
copy code

 

You can see the output result, add it in front of function! , +, - and even commas can have the effect of being executed immediately after the function is defined, while (), ! , +, -, = and other operators convert function declarations into function expressions, eliminating the ambiguity between the javascript engine identifying function expressions and function declarations, and telling the javascript engine that this is a function expression, not a function declaration, which can be found in Put parentheses after it and execute the code of the function immediately.

Parentheses are the safest thing to do because ! , +, - and other operators will also operate with the return value of the function, sometimes causing unnecessary trouble.

But what's the use of writing this way?

The concept of private scope is not used in javascript. If you declare some variables in the global or local scope on a project developed by multiple people, they may be accidentally overwritten by others with variables of the same name. According to the javascript function The characteristics of the scope chain, you can use this technique to imitate a private scope, use an anonymous function as a "container", the "container" can access external variables, and the external environment cannot access the variables inside the "container", so ( function(){…} )() Internally defined variables will not conflict with external variables, commonly known as "anonymous wrapper" or "namespace".

JQuery uses this method, wrapping the JQuery code in ( function (window,undefined){...jquery code...} (window), when calling the JQuery code in the global scope, it can protect the internal variables of JQuery.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324901403&siteId=291194637