gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:32:22 25 4
gpt4 key购买 nike

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

总结一下我的 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
}

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

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

更新:

所以要将其简化为正确的(请参阅我的评论)?

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));

最佳答案

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

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);

关于Javascript : Best way to declare functions to be used globally?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5119958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com