Javascript:声明要全局使用的函数的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5119958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:01:10  来源:igfitidea点击:

Javascript : Best way to declare functions to be used globally?

javascriptjquery

提问by wilsonpage

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 file.

我的javascript文件变得非常大(3000多行),我对如何布局我的文件和delare函数感到困惑,以便它们可以在文件中的任何地方调用。

To summarise my JS file looks a little like this at the moment:

总结一下我的 JS 文件现在看起来有点像这样:

//ALL GLOBAL VARIABLES FIRST DECLARED HERE
var var1 , var2 ,var3

$(document).ready(function(){

//JQUERY STUFF

});

//ALL FUNCTIONS THAT NEED TO BE GLOBAL DECLARED HERE
function myFunction(){
//do some stuff here
}

I am running into problems with this as some functions I call in places don't seem to be declared at the time of calling or aren't available globaly. It's all very confusing now!

我遇到了这个问题,因为我在某些地方调用的某些函数似乎没有在调用时声明或在全局范围内不可用。现在一切都非常混乱!

Could someone suggest the best way to layout a big js/jquery file with certain JS Functions, Objects and Variables available to be referenced anywhere in the file.

有人可以建议布局大型 js/jquery 文件的最佳方法,其中某些 JS 函数、对象和变量可在文件中的任何位置引用。

UPDATE:

更新:

So to simplify it this correct (see my comments)?

所以为了简化它是正确的(见我的评论)?

window.MainModule = (function($, win, doc, undefined) {//WHAT IS BEING PASSED IN HERE?
    var foo, bar, modules; //VARIABLES ACCESSIBLE ANYWHERE

    var modules["foobar"] = (function() {//WHAT IS A MODULE? WHEN WOULD I USE A SEPERATE MODULE?
        var someFunction = function() { ... };//DECLARING MY FUNCTIONS?

        ...

        return { 
            init: someFunction,//IS THIS WHERE I USE/BIND MY FUNCTIONS TO EVENTS AND ELEMENTS?
            ... 
        };
    }());

    // hoist a variable into global scope
    window.Global = someLocal;

    return { 
        init: function() {//FUNCTION TO INIT ALL MODULES?
            for (var key in modules) {
                modules[key].init();
            }
        }
    };
}(jQuery, this, document));

采纳答案by Jeff Parker

The modules section isn't properly defined ... here's a slightly tidied up example.

模块部分没有正确定义......这是一个稍微整理的例子。

window.MainModule = (function($, win, doc, undefined) {
    var modules = {};

    // -- Create as many modules as you need ...
    modules["alerter"] = (function(){
        var someFunction = function(){ alert('I alert first'); };

        return { 
            init: someFunction
        };
    }());

    modules["alerter2"] = (function(){
        var someFunction = function(){ alert('I alert second'); };

        return { 
            init: someFunction
        };
    }());

    return { 
        init: function(){
            for (var key in modules){
                modules[key].init();
            }
        }
    };
}(jQuery, this, document));

$(window.MainModule.init);

回答by Raynos

// 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 xinside 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.

var x在主闭包内声明的任何内容都可以在整个函数中使用。当然,除非您设置它,否则它不会设置为您期望的设置。

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

将加载和流拆分代码控制为在您的自执行闭包中自动执行的内容以及需要inited由您的控制器使用页面/用户特定参数手动执行的内容。

回答by jjrdk

You can either declare them in Window scope:

您可以在 Window 范围内声明它们:

window.variableName = myVariable;

or you can omit the var, which is the same as declaring something in window scope:

或者您可以省略 var,这与在窗口范围内声明某些内容相同:

variableName = myVariable;