Self-executed function: automatically executed function. It is already running when it is explained. Generally, functions are executed only when called.
General Format of Self-executed functions: (function () {function body })();
In addition, self-executed functions generally have an anonymous function in the form of function.
The following code creates a namespace mySpace in the window object and encapsulates the methods in the self-execution function under the mySpace namespace, so that we can call some functions in this self-execution function.
Copy codeThe Code is as follows:
(Function (){
// Obtain the object by id
Function $ (id) {return document. getElementById (id );}
// Internal functions cannot be called in the outer layer
Function _ setStyle (id, styleName, styleValue ){
$ (Id). style [styleName] = styleValue;
}
// Create a pseudo namespace
Window. mySpace = {};
// Encapsulate the internal function _ setStyle In the mySpace namespace
// When calling, use window. mySpace. setStyle (id, styleName, styleValue)
Window. mySpace. setStyle = _ setStyle;
})();
// The following is the test code.
Window. onload = function (){
// Set the text color of the object whose id is test to red
Window. mySpace. setStyle ("test", "color", "# f00 ");
}
So what are the advantages of this encapsulation method?
Of course, it protects methods, variables, and attributes in self-executed functions. This makes the code more secure.
If this method is not used, the following methods can also be implemented.
Copy codeThe Code is as follows:
Window. mySpace = {};
Window. mySpace. $ = function (id) {return document. getElementById (id );}
Window. mySpace. setStyle = function (id, styleName, styleValue ){
Window. mySpace. $ ("test"). style [styleName] = styleValue;
}
// The following is the test code.
Window. onload = function (){
Window. mySpace. setStyle ("test", "backgroundColor", "# f00 ");
Window. mySpace. setStyle ("test", "color", "# fff ");
}
The above code and self-executed functions are actually the same.
After comparison, we can find that the second method is more intuitive and easy to understand. But the encapsulation process is missing, and the code is completely exposed.