namespaces, you know the primary purpose is to avoid conflicts. Here's how to build your own JavaScript namespace.
Creating a JavaScript namespace is simply a matter of putting your own functions, objects, variables, and so on in a pseudo namespace, wrapped in an anonymous function.
Copy Code code as follows:
(function () {
function $ (ID) {
return document.getElementById (ID);
}
function Alertnodename (ID) {
Alert ($ (ID). nodename);
}
})();
Using this pseudo namespace allows you to encapsulate and protect all of your functions, objects, and variables, and because they are in a function, you can access each other. However, scripts other than pseudo namespaces cannot use these functions.
To enable these functions to be called by scripts outside of the pseudo namespace, we first create a Window object.
Copy Code code as follows:
(function () {
if (!window.mynamespace) {window[' MyNamespace ']={};}
function $ (ID) {
return document.getElementById (ID);
}
function Alertnodename (ID) {
Alert ($ (ID). nodename);
}
})();
Then rename the function to be global (or not rename it) and assign it to the Window object window[' MyNamespace '.
Copy Code code as follows:
(function () {
if (!window.mynamespace) {window[' MyNamespace ']={};}
function $ (ID) {
return document.getElementById (ID);
}
function Alertnodename (ID) {
Alert ($ (ID). nodename);
}
window[' MyNamespace ' [' shownodename '] = alertnodename;
})();
So we create a namespace of our own.
Copy Code code as follows:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
< title> New Document </TITLE>
<meta name= "generator" content= "EditPlus" >
<meta NA Me= "Author" content= "" >
<meta name= "Keywords" content= "" >
<meta name= "Description" CO Ntent= "" >
<script language= "JavaScript" >
<!--
(function () {
func tion $ (id) {
return document.getElementById (ID);
}
function alertnodename (ID) {
alert ($ (ID). nodename);
}
window[' mynamespace '] = {};
window[' MyNamespace ' [' shownodename '] = alertnodename;
}) ();
function Test () {
mynamespace.shownodename ("T");
}
//-->
</SCRIPT>
</HEAD>
<body onload= "TeSt () ">
<input type=" text "name=" T "id=" T "value=" Test ">
</BODY>