However, when adding attributes to a namespace in a different file, the first step is to ensure that the namespace is already present and does not cause any damage to the existing namespaces. Can be implemented through a Non-destructive namespace function:
Copy Code code as follows:
var kui = Kui | | {};
Kui.utils = Kui.utils | | {};
KUI.utils.namespace = function (ns) {
var parts = Ns.split ("."),
Object = Kui,
I, Len;
if (parts[0] = = "Kui") {
Parts = Parts.slice (1);
}
for (i = 0, len = parts.length i < len; i+=1) {
if (!object[parts[i]]) {
Object[parts[i]] = {};
}
Object = Object[parts[i]];
}
return object;
};
Usage:
Copy Code code as follows:
KUI.utils.namespace ("Kui.common");
KUI.utils.namespace ("KUI.common.testing");
KUI.utils.namespace ("KUI.modules.function.plugins");
KUI.utils.namespace ("format");
Take a look at what's going on after Kui:
Copy Code code as follows:
{
"Utils": {},
"Common": {
"Testing": {}
},
"Modules": {
' function ': {
"Plugins": {}
}
},
' Format ': {}
}
Disadvantages of the namespace pattern
1. Need to enter longer characters, and need longer parsing time;
2. Dependence on a single global variable, that is, any code can modify the global instance, and other code will get the modified instance.