+function(){}();The plus sign here can also be replaced with other unary operators such as!, ~, and the effect is equivalent to:
(function() { console.log("Foo!"); })(); // or (function() { console.log("Foo!"); }());Without this plus sign, the parser will think that function is the beginning of a function declaration, and the subsequent() will cause a syntax error. When the + sign is added before the function, it becomes a function expression, and when a () is added after the function expression, it becomes an immediately executed function.
Let’s take a look at the function of the exclamation point in front of the js function:
1. JS function declaration form
function fnA(){alert('msg');} //Declaration definition function2. JS function expression form
var func = function(agr1,arg2){ //Create anonymous function alert(arg1 + ' ' + arg2);}3. Common formats for executing immediately after JS anonymous function declaration
(function() { /* code */ })();illustrate
1. The first pair of brackets surrounding the function (function(){}) returns the unnamed function to the script, and then a pair of empty brackets immediately executes the returned unnamed function, with the parameters of the anonymous function in the brackets.
2. Use brackets to define the function body, and the parser will call the definition function in the form of a function expression. In other words, any method that can turn a function into a function expression can enable the parser to call the defined function correctly. And! is one of them, and + - || has such a function.
3. The function of this function is mainly anonymous and automatic execution.