Home  >  Article  >  Web Front-end  >  A brief introduction to javaScript NameSpace_Basic knowledge

A brief introduction to javaScript NameSpace_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:28:281136browse

Creating a JavaScript namespace is actually very simple. You only need to put your own functions, objects, variables, etc. in a pseudo namespace, that is, wrap it with an anonymous function.

Copy code The code is as follows:

(function(){
function $(id ; ;


Use this pseudo namespace to encapsulate and protect all your functions, objects, and variables, and because they are located in a function, they can also access each other. However, scripts outside the pseudo namespace cannot use these functions.
In order to make these functions callable by scripts outside the pseudo namespace, we first create a window object.



Copy code

The code is 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 globalized (or not rename it) and assign it to window object window['myNameSpace'].



Copy code

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;
})();


                    We created our own namespace.



Copy code

The code is as follows: New Document










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