Self-executed anonymous functions in Javascript
Format:
(function(){ //code})();Explanation: This is quite elegant code (it 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 then a pair of empty brackets immediately executes the returned unnamed function, with parameters of the anonymous function in the brackets.
Here is an example with parameters:
(function(arg){ alert(arg+100); })(20); // This example returns 120.Important use: You can use it to create a namespace. As long as you write all your code in this special function wrapper, the external cannot be accessed 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 encapsulate and protect all your functions, objects, and variables with this pseudo-namespace. Moreover, since they are in the same function, they can be referenced to each other. In order to globalize the protected code, a pair of brackets tells the browser to execute the returned anonymous function immediately, and during execution, assign __addClass() to a method of window, so that only addClass can be executed externally and __addClass is protected. I can call it like this: mySpace.addClass('oneId','font-width','bold')