Format:
(Function (){
// Code
})();
Explanation: this is a pretty elegant code (it may be confusing if you see it for the first time :)). The first pair of parentheses in the function () {}) returns the Untitled function to the script, then a pair of empty parentheses immediately execute the returned untitled function, which contains the parameters of the anonymous function.
Here is an example with parameters:
(Function (arg ){
Alert (arg + 100 );
}) (20 );
// In this example, 120 is returned.
Important purpose: You can use it to create a namespace. As long as you write all your code in this special function package, the outside will not be accessible unless you allow
(Function (){
Function $ (id ){
Return document. getElementById (id );
}
Function _ addClass (id, className, classValue ){
$ (Id). style. className = classValue;
}
Window ['myspace '] = {};
Window ['myspace '] ['addclass'] =__ addClass;
})();
In the preceding example, you can use this pseudo namespace to encapsulate and protect all your functions, objects, and variables. Besides, because they are in the same function, they can be referenced from each other. To render the protected code, a pair of parentheses tell the browser to immediately execute the returned anonymous function, and assign _ addClass () to a window method during execution, in this way, only addClass can be executed externally, while _ addClass is protected. I can call it like this: mySpace. addClass ('oneid', 'font-width', 'bold ');
Author "disablebb"