Self-executing anonymous function in Javascript
Format:
(function(){ //代码 })();
Explanation: This is quite elegant code (you may be confused if you see it for the first time :)). The first pair of brackets surrounding the function (function(){}) returns an unnamed function to the script, and the following pair Empty parentheses immediately execute the returned unnamed function, and the parameters in the parentheses are the parameters of the anonymous function.
Let’s take an example with parameters:
(function(arg){ alert(arg+100); })(20); // 这个例子返回120。
Important use: You can use it to create a namespace. As long as you write all your code in this special function wrapper, it will not be accessible from the outside unless you allow it
(function(){ function $(id){ return document.getElementById(id); } function __addClass(id,className,classValue){ $(id).style.className=classValue; } window['mySpace']={}; window['mySpace']['addClass']=__addClass; })();
The above example can use this pseudo namespace to encapsulate and protect all its functions, objects and variables. And, since they are in the same function, they can reference each other. In order to globalize the protected code, the subsequent pair of parentheses tells the browser to immediately execute the returned anonymous function, and assign __addClass() to a method of window during execution, so that only addClass can be executed externally. __addClass is protected. I can call it like this: mySpace.addClass('oneId','font-width','bold')