However, when adding attributes to a namespace in different files, you must first ensure that the namespace already exists, and at the same time do not cause any damage to the existing namespace. This can be achieved through non-destructive namespace functions:
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:
KUI.utils.namespace("KUI.common") ;
KUI.utils.namespace("KUI.common.testing");
KUI.utils.namespace("KUI.modules.function.plugins");
KUI.utils.namespace("format ");
Look at what KUI has after going through the above:
{
"utils": {},
"common": {
"testing": {}
},
"modules": {
"function": {
"plugins": {}
}
},
"format": {}
}
Disadvantages of the namespace pattern
1. Need to enter longer characters and require longer parsing time;
2. Dependence on a single global variable, that is, any code can modify the global instance, and other codes will get the modified Example.