Learning ES6 encountered the self-executing function, feel the need to write down, on the one hand to deepen their memories, on the other hand can also share to everyone.
What is a self-executing function?
The self-executing function is meant to be an anonymous function that does not pollute the global variable namespace, which is equivalent to creating a scope of its own, and here's how it works:
function foo () {...} This is the definition, Declaration; the definition simply lets the interpreter know that it exists, but does not run. Foo (); This is the statement, Statement; The interpreter will run it when it encounters a statement.
The function above is a traditional function, it is a bit verbose, and it will pollute the global namespace, so it is not friendly to us, so the self-executing function appears, the following wording:
(function foo () {...}) ();
(function foo () {...} ());//recommended to use this form
The code block above is the self-executing function of two forms, it is recommended to use the following form, specifically, I do not know, perhaps because the package is more like encapsulating a function, you can understand. Traditional functions such as: function foo (...) {}, it is actually a declaration, for the interpreter, as if you had written a string "function foo (...) {} ", it needs to be executed using a parse function, such as Eval (). So put () directly behind the declaration is not executed, this is the wrong syntax. How do you get it right? It's easy to say, as long as you turn the declaration into an expression. This is the function in the code block above.
I hope you will understand, and I would be honored.
Self-executing functions in JavaScript