Home  >  Article  >  Web Front-end  >  Pseudo namespace encapsulation method of javascript self-executing function_javascript skills

Pseudo namespace encapsulation method of javascript self-executing function_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:13:281385browse

Self-executing function: A function that executes automatically. It is already running when it is interpreted. Generally, functions are executed when they are called.
The general format of a self-executing function: (function() { function body })();
Moreover, self-executing 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-executing function under the mySpace namespace so that we can call some functions in this self-executing function.

Copy code The code is as follows:

(function() {
//According to id Get the object
function $(id) { return document.getElementById(id); }

//Internal function 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 with id test to red
window.mySpace.setStyle( "test", "color", "#f00");
}

So what are the benefits of this packaging method?

Of course, it protects the methods, variables, attributes, etc. within the self-executing function. This makes the code more secure.

If this method is not used, then the following method can also be implemented.
Copy code The 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 the functions implemented by the self-executing function Actually it's the same.

After comparison, we can find that the second method is more intuitive and easy to understand. But without the encapsulation process, the code is completely exposed.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn