Anonymous functions can effectively control the scope of variables and construct closures (Closure) to prevent pollution of global variables. In JavaScript, there are several ways to write anonymous functions:
Error mode: syntax error warning
function () {
//Insert code here
} ();
Mode one: function literal (functions Literal)
Declare the function object first, and then execute.
(function () {
//Insert code here
}) ();
Mode two: Precedence expression (Prior Expression)
Because JavaScript executes an expression from inside to outside, parentheses are used to enforce a declared function.
(function () {
//Insert code here
} ());
Mode III: void operator (void Operator)
Use the Void operator to perform a separate operand.
void function () {
//Insert code here
} ();
Technically speaking, these three code patterns are equivalent. But in practical applications, such as YUI, JQuery and other frameworks, pattern one is more widely used.