JavaScript is not like C # or Java, there is a special namespace and package syntax support, when JS complex to a certain extent, especially the reference to a large number of third-party JS framework and Class library, naming conflicts will become a serious problem, Therefore, it is important to build a namespace using JS's own workaround.
The simplest way to implement namespaces is the following code example:
This is pseudo-code:
var com;
if (!com) com = {}; First level domain name
Com. Moduleclass = {}; Second-level domain name
Com. Moduleclass. Function name 1=function () {
function body;
}
Com. Moduleclass. Function name 2=function () {
function body;
}
You can also establish a mechanism for registering a multilevel namespace:
1. Namespace Registration Tool Class
var Namespace = new Object ();
Namespace.register = function (path) {
var arr = Path.split (".");
var ns = "";
for (Var i=0;i<arr.length;i++) {
if (i>0) ns + = ".";
NS + = Arr[i];
Eval ("If" (typeof ("+ ns +") = = ' undefined ') "+ ns +" = new Object (); ");
}
}
2. Register namespace Com.boohee.ui
Namespace.register ("Com.boohee.ui");
3. Using namespaces
Com.boohee.ui.TreeGrid = function () {
This.sayhello = function (name) {
Alert ("Hello" + name);
}
}
var t = new Com.boohee.ui.TreeGrid ();
T.sayhello ("UID");
===========================================================================
/*** constructs a namespace ***/
/*
* If (typeof (window). Com) = = "undefined")//can also be used: if (typeof (Com) = = "undefined")
{
Window. Com = {};//can also be used: window. Com = new Object ();
}
*/
Level One: Brclib
if (typeof (brclib) = = "undefined")
{
Brclib = new Object ();
}
Level Two: Brclib.javascript
if (typeof (brclib.javascript) = = "undefined")
{
Brclib.javascript = {};
}
Level Three: BrcLib.JavaScript.File
if (typeof (BrcLib.JavaScript.File) = = "undefined")
{
BrcLib.JavaScript.File = {};
}
Level Three: BrcLib.JavaScript.Message
if (typeof (BrcLib.JavaScript.Message) = = "undefined")
{
BrcLib.JavaScript.File = {};
}
Static methods
BrcLib.JavaScript.Message.ShowMessage = function (ms)
{
Alert (MS);
}
You must use the new method
BrcLib.JavaScript.Message.prototype.formatString = function (format)
{
Code
}
JS Multilevel namespaces