Javascript is more casual compared to other programming languages, so Javascript code is full of all kinds of weird writing methods. Sometimes you can see flowers in the fog. Of course, being able to understand various types of writing methods is also a further in-depth understanding of the characteristics of Javascript language.
( function(){…} )() and ( function (){…} () ) are two common ways to immediately execute functions in JavaScript. At first I thought it was an anonymous function wrapped in a bracket, and then added a bracket to call the function. Finally, I achieved the purpose of executing it immediately after the function is defined. Later, I found that the reason for adding brackets was not the case. To understand the execution of functions immediately, you need to first understand some basic concepts of functions.
Function declarations, function expressions, anonymous functions
Function declaration: function fnName () {…}; Use the function keyword to declare a function, and then specify a function name, called function declaration.
Function expression var fnName = function () {…};Declare a function using the function keyword, but does not name the function. Finally, the anonymous function is assigned a variable, called a function expression, which is the most common form of function expression syntax.
Anonymous function: function () {}; Use the function keyword to declare a function, but the function is not named, so it is called anonymous function. Anonymous functions belong to function expressions. Anonymous functions have many functions. If you assign a variable, you create a function, and if you assign an event, you become an event handler or create a closure, etc.
The difference between function declaration and function expression is that 1. When parsing javascript code, the Javascript engine will 'function declaration promotion' (Function declaration Hoisting) function declaration on the current execution environment (scope). The function expression must wait until the Javascirtp engine executes to its line before parsing the function expression from top to bottom line. 2. The function expression can be called immediately with brackets after the function expression. The function declaration cannot be done and can only be called in the form of fnName(). Here are two examples of the differences between the two.
fnName();function fnName(){ ...}//Normal, because 'promoting' the function declaration, function calls can be fnName();var fnName=function(){ ...}//An error is reported, the variable fnName has not saved a reference to the function, and the function call must be after the function expression var fnName=function(){ alert('Hello World');}();//Parcels are added after the function expression. When the javascript engine parses here, the function can be called immediately function fnName(){ alert('Hello World');}();//There will not be an error, but the javascript engine only parses the function declaration, ignores the subsequent brackets, and the function declaration will not be called function(){ console.log('Hello World'); }();//The syntax error, although anonymous functions belong to function expressions, no assignment operation is performed, //So the javascript engine treats the function keyword at the beginning as a function declaration, and reports an error: a function name is requiredAfter understanding some basic functions concepts, I looked back at the two ways to write ( function(){…} )() and ( function (){…} () ) immediately. At first I thought it was an anonymous function wrapped in a bracket and added a bracket to call the function immediately. At that time, I didn't know why I had to add brackets. Later I realized that if I had to add brackets after the function body, I could call it immediately. Then this function must be a function expression, not a function declaration.
(function(a){ console.log(a); //firebug output 123, use the () operator})(123); (function(a){ console.log(a); //firebug output 1234, use the () operator}(1234)); !function(a){ console.log(a); //firebug output 12345, use! Operator }(12345); +function(a){ console.log(a); //firebug output 123456, use the + operator}(123456); -function(a){ console.log(a); //firebug output 1234567, use the - operator}(1234567); var fn=function(a){ console.log(a); //firebug output 12345678, use the = operator}(12345678)You can see the output result and add it before the function! , +, - and even commas can be used to execute immediately after the function is defined, and (),! Operators such as +, -, = convert function declarations into function expressions, eliminating the ambiguity between the javascript engine identifying function expressions and function declarations, telling the javascript engine that this is a function expression, not a function declaration, you can add parentheses after it and execute the function's code immediately.
Adding brackets is the safest way to do it, because! Operators such as , +, and - will also perform operations with the function's return value, which sometimes causes unnecessary trouble.
But what's the use of writing this way?
There is no concept of private scope in JavaScript. If you declare some variables in global or local scope on a project developed by multiple people, it may be overwritten by others with the same name. According to the characteristics of the scope chain of JavaScript functions, this technique can be used to imitate a private scope and use an anonymous function as a "container". The "container" can access external variables, while the external environment cannot access variables inside the "container", so the variables defined inside ( function(){…} )() will not conflict with external variables, commonly known as "anonymous wrapper" or "namespace".
JQuery uses this method. When JQuery code is wrapped in ( function (window, undefined){…jquery code…} (window), it can protect the internal variables of JQuery when calling JQuery code in the global scope.
This article is a personal understanding and compilation. If there are any errors, please point them out. The views in the article are referenced from:
"Authoritative Guide to JavaScript" and "Advanced Programming"