JavaScript Namespace

后端 未结 11 1472
暗喜
暗喜 2020-12-15 07:25

I want to create a global namespace for my application and in that namespace I want other namespaces:

E.g.

Dashboard.Ajax.Post()

Dashboard.RetrieveC         


        
11条回答
  •  [愿得一人]
    2020-12-15 07:47

    Implementation:

    namespace = function(packageName)
    {
        // Local variables.
        var layers, layer, currentLayer, i;
    
        // Split the given string into an array.
        // Each element represents a namespace layer.
        layers = packageName.split('.');
    
        // If the top layer does not exist in the global namespace.
        if (eval("typeof " + layers[0]) === 'undefined')
        {
            // Define the top layer in the global namesapce.
            eval(layers[0] + " = {};");
        }
    
        // Assign the top layer to 'currentLayer'.
        eval("currentLayer = " + layers[0] + ";");
    
        for (i = 1; i < layers.length; ++i)
        {
            // A layer name.
            layer = layers[i];
    
            // If the layer does not exist under the current layer.
            if (!(layer in currentLayer))
            {
                // Add the layer under the current layer.
                currentLayer[layer] = {};
            }
    
            // Down to the next layer.
            currentLayer = currentLayer[layer];
        }
    
        // Return the hash object that represents the last layer.
        return currentLayer;
    };
    


    Result:

    namespace('Dashboard.Ajax').Post = function() {
        ......
    };
    
    namespace('Dashboard.RetrieveContent').RefreshSalespersonPerformanceContent = function() {
        ......
    };
    


    Gist:

    namespace.js

提交回复
热议问题