JavaScript Namespace

后端 未结 11 1503
暗喜
暗喜 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: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 || {}));
    

提交回复
热议问题