JavaScript Namespace

后端 未结 11 1397
暗喜
暗喜 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 08:02

    I believe the module pattern might be right up your alley. Here's a good article regarding different module patterns.

    http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

    0 讨论(0)
  • 2020-12-15 08:03

    Here is a very good article on various "Module Patterns" in JavaScript. There is a very nice little section on how you can augment modules, or namespaces and maintain a cross-file private state. That is to say, the code in separate files will be executed sequentially and properly augment the namespace after it is executed.

    I have not explored this technique thoroughly so no promises... but here is the basic idea.

    dashboard.js

    (function(window){
    
        var dashboard  = (function () { 
            var my = {}, 
                privateVariable = 1; 
    
            function privateMethod() { 
                // ... 
            } 
    
            my.moduleProperty = 1; 
            my.moduleMethod = function () { 
                // ... 
            }; 
    
            return my; 
        }());
    
        window.Dashboard = dashboard;
    })(window);
    

    dashboard.ajax.js

    var dashboard = (function (my) { 
        var _private = my._private = my._private || {}, 
            _seal = my._seal = my._seal || function () { 
                delete my._private; 
                delete my._seal; 
                delete my._unseal; 
            }, 
            _unseal = my._unseal = my._unseal || function () { 
                my._private = _private; 
                my._seal = _seal; 
                my._unseal = _unseal; 
            }; 
    
        // permanent access to _private, _seal, and _unseal
    
        my.ajax = function(){ 
            // ...
        }
    
        return my; 
    }(dashboard || {}));
    

    dashboard.retrieveContent.js

    var dashboard = (function (my) { 
        var _private = my._private = my._private || {}, 
            _seal = my._seal = my._seal || function () { 
                delete my._private; 
                delete my._seal; 
                delete my._unseal; 
            }, 
            _unseal = my._unseal = my._unseal || function () { 
                my._private = _private; 
                my._seal = _seal; 
                my._unseal = _unseal; 
            }; 
    
        // permanent access to _private, _seal, and _unseal
    
        my.retrieveContent = function(){ 
            // ...
        }
    
        return my; 
    }(dashboard || {}));
    
    0 讨论(0)
  • 2020-12-15 08:09

    You could do something like this...

    HTML page using namespaced library:

    <html>
    <head>
        <title>javascript namespacing</title>
        <script src="dashboard.js" type="text/javascript"></script>
        <script src="ajax.js" type="text/javascript"></script>
        <script src="retrieve_content.js" type="text/javascript"></script>
        <script type="text/javascript">
            alert(Dashboard.Ajax.Post());
            alert(Dashboard.RetrieveContent.RefreshSalespersonPerformanceContent());
            Dashboard.RetrieveContent.Settings.Timeout = 1500;
            alert(Dashboard.RetrieveContent.Settings.Timeout);
        </script>
    </head>
    
    <body>
        whatever...
    </body>
    
    </html>
    

    Dashboard.js:

    (function(window, undefined){
        var dashboard = {};
        window.Dashboard = dashboard;
    })(window);
    

    Ajax.js:

    (function(){
        var ajax = {};
        ajax.Post = function() { return "Posted!" };
        window.Dashboard.Ajax = ajax
    })();
    

    Retrieve_Content.js:

    (function(){
        var retrieveContent = {};
        retrieveContent.RefreshSalespersonPerformanceContent = function() { 
            return "content retrieved"
        };
    
    
        var _contentType;
        var _timeout;
        retrieveContent.Settings = {
            "ContentType": function(contentType) { _contentType = contentType; },
            "ContentType": function() { return _contentType; },
            "Timeout": function(timeout) { _timeout = timeout; },
            "Timeout": function() { return _timeout; }
        };
    
        window.Dashboard.RetrieveContent = retrieveContent;
    
    })();
    

    The Dashboard.js acts as the starting point for all namespaces under it. The rest are defined in their respective files. In the Retrieve_Content.js, I added some extra properties in there under Settings to give an idea of how to do that, if needed.

    0 讨论(0)
  • I highly recommend you use this technique:

    https://github.com/mckoss/namespace

      namespace.lookup('com.mydomain.mymodule').define(function (ns) {
      var external = namespace.lookup('com.domain.external-module');
    
      function myFunction() {
        ...
      }
    
      ...
    
      ns.extend({
        'myFunction': myFunction,
         ...
      });
    });
    

    I've been using this pattern for a couple of years; I wish more libraries would do the same thing; it's made it much easier for me to share code across my different projects as well.

    0 讨论(0)
  • 2020-12-15 08:12

    i wrote this function to simplify creating namespaces. Mabey it will help you.

    function ns(nsstr) {
        var t = nsstr.split('.');
        var obj = window[t[0]] = window[t[0]] || {};
        for (var i = 1; i < t.length; i++) {
            obj[t[i]] = obj[t[i]] || {};
            obj = obj[t[i]];
        }
    }
    
    ns('mynamespace.isawesome.andgreat.andstuff');
    mynamespace.isawesome.andgreat.andstuff = 3;
    
    console.log(mynamespace.isawesome.andgreat.andstuff);
    
    0 讨论(0)
提交回复
热议问题