No difference.
You need to understand the principle of IIFE, let me briefly explain:
IIFE is not required. To be more traditional, you can write it like this:
So why IIFE?
1. The traditional method is cumbersome, and the definition and execution are written separately;
2. The traditional method directly pollutes the global namespace (global object in the browser, such as window)
So, developers want to find a way to solve the above problems. So is it okay to write like this?
function foo(...){}();
Of course not, but why? Because the function foo(...){} part is just a statement, to the interpreter, it is like you wrote a string "function foo(...){}", which requires the use of parsing functions, such as eval () to execute it. So putting () directly after the statement will not be executed, which is wrong syntax.
How to make it right? It's easy to say, just turn the statement into an expression (Expression).
In fact, there are many ways to transform expressions. The most common way is to wrap the function declaration with a pair of (), so it becomes:
This is equivalent to:
But the way we said it was impossible to write before can actually be wrapped directly in parentheses. This is also an equivalent expression:
(function foo(){...}());
So you ask, is there any difference? Very simple: No~
In addition, as I just said there are many ways to transform expressions, there are indeed many other ways to write them, such as:
!function foo() {...}();
or
function foo() {...}();
These are all fine.
I personally prefer to use void to convert expressions, because this keyword does not have a return value. But this point really doesn’t matter, just treat me as a “tortoise”…
OK, the so-called not polluting the global namespace is because IIFE creates a new function scope, and your real business code is encapsulated in it, so it will naturally not touch the global object. If you need the global object, pass to IIFE:
I have written a series here, one of which talks about scope and naming promotion. The knowledge points in it are helpful for understanding IIFE. If you are interested, you can continue reading in depth: http://www.jb51 .net/article/75090.htm
Method one, call the function and get the return value. Forces the function to be executed directly and then returns a reference, which is then called and executed
Method two, call the function and get the return value. The coercion operator causes function calls to execute
(function(){})(); is to parse the function as an expression and then execute the parsed function
Equivalent to var a = function(){}; a(); a gets the function
(function(){}()); is to directly execute the function expression and execution as a statement,
Equivalent to var a = function(){}(); a gets the result
The end result is the same,
() just plays the role of self-execution
There are many more like ()
For example function (){}
This is equal to (function (){}). Generally, (function (){}) has another effect, which is to avoid global variables