[removed] Best way to declare functions to be used globally?

前端 未结 3 994
长发绾君心
长发绾君心 2021-02-04 06:20

My javascript file is getting pretty big (3000+ lines) and I\'m getting confused as to how to layout my file and delare functions so that they can called anywhere in the

3条回答
  •  甜味超标
    2021-02-04 07:06

    // We always use closures don't we?
    window.MainModule = (function($, win, doc, undefined) {
        var foo, bar, modules; // List of local variables. 
    
        var modules["foobar"] = (function() {
            var someFunction = function() { ... };
    
            ...
    
            return { 
                init: someFunction,
                ... 
            };
        }());
    
        // hoist a variable into global scope
        window.Global = someLocal;
    
        return { 
            init: function() {
                for (var key in modules) {
                    modules[key].init();
                }
            }
        };
    }(jQuery, this, document));
    
    // Let's kick off the MainModule on $.ready
    // I recommend you do this in your `html` with page specific data.
    $(window.MainModule.init);
    

    [[Disclaimer]]: This is a pseudo-code module with some standard code excluded for brevity.

    Anything declared with var x inside your main closure is available throughout the entire function. Of course it won't be set to what you expect it to be set unless you set it.

    To control loading and flow split code into what's automatically executed in your self executing closure and what needs to manually inited by your controller with page/user specific parameters.

提交回复
热议问题