Namespace. The main purpose is to avoid conflicts. The following describes how to create your own JavaScript namespace. Creating a JavaScript namespace is actually very simple. You only need to put your own functions, objects, variables, and so on in a pseudo namespace, Which is packaged with an anonymous function.
The Code is as follows:
(Function (){
Function $ (id ){
Return document. getElementById (id );
}
Function alertNodeName (id ){
Alert ($ (id). nodeName );
}
})();
Using this pseudo-namespace can encapsulate and protect all functions, objects, and variables of the user, and because they are in a function, they can also access each other. However, scripts outside the pseudo namespace cannot use these functions.
To enable these functions to be called by scripts outside the pseudo namespace, we first create a window object.
The Code is as follows:
(Function (){
If (! Window. myNamespace) {window ['mynamespace'] = {};}
Function $ (id ){
Return document. getElementById (id );
}
Function alertNodeName (id ){
Alert ($ (id). nodeName );
}
})();
Rename the function to be converted (or do not rename it) and assign it to the window Object window ['mynamespace'].
The Code is as follows:
(Function (){
If (! Window. myNamespace) {window ['mynamespace'] = {};}
Function $ (id ){
Return document. getElementById (id );
}
Function alertNodeName (id ){
Alert ($ (id). nodeName );
}
Window ['mynamespace'] ['shownodename'] = alertNodeName;
})();
In this way, we create our own namespace.
The Code is as follows:
New Document