Javascript namespace pattern

  • 2020-03-26 21:46:53
  • OfStack

However, when adding attributes to a namespace in different files, you first need to make sure that the namespace already exists without any damage to the existing namespace. Can be achieved by 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");

Take a look at what KUI has after the above:


{
    "utils": {},
    "common": {
        "testing": {}
    },
    "modules": {
        "function": {
            "plugins": {}
        }
    },
    "format": {}
}

Disadvantages of the namespace pattern

1. Longer characters need to be input and longer parsing time is required;
2. The dependency on a single global variable, that is, any code can modify the global instance, and other code will get the modified instance.


Related articles: