JavaScript Namespace

后端 未结 11 1504
暗喜
暗喜 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:09

    You could do something like this...

    HTML page using namespaced library:

    
    
        javascript namespacing
        
        
        
        
    
    
    
        whatever...
    
    
    
    

    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.

提交回复
热议问题