An in depth analysis of the plus sign and exclamation mark before JavaScript function

  • 2021-07-02 23:09:53
  • OfStack


+function(){}(); 

The plus sign here can also be replaced by! Other 1 yuan operators, such as, ~, etc., have the effect of:


(function() { console.log("Foo!"); })(); 
// or 
(function() { console.log("Foo!"); }()); 

Without this plus sign, the parser will assume that function is the beginning of a function declaration, and the following () will cause a syntax error. When function is preceded by a + sign, it becomes a function expression, and when a () is added after the function expression, it becomes a function to be executed immediately.

Let's look at the exclamation point before the js function:

1. JS function declaration form


function fnA(){alert('msg');} // Declaratively defined function  

2. JS function expression form


var func = function(agr1,arg2){ // Create an anonymous function 
alert(arg1 + ' ' + arg2);
} 

3. Common format for JS anonymous functions to execute immediately after declaration


(function() { /* code */ })();

Description

1. The first pair of parentheses surrounding the function (function () {}) returns the unnamed function to the script, followed by a pair of empty parentheses immediately executing the returned unnamed function with the parameters of the anonymous function inside the parentheses.

2. Use parentheses to wrap the definition function body, and the parser will call the definition function in the form of function expression. That is to say, anything that can turn a function into a function expression can make the parser call the definition function correctly. And! Is one of them, and +-has this function.

3. The main function of this function is anonymity and automatic execution


Related articles: