Javascript 这些函数将以什么顺序执行?
我正在重写我的一个项目,这次我决定使用自调用函数来保存一些代码,但我变得非常不确定这是否可行,因为我不希望在page加载+运行Javascript 这些函数将以什么顺序执行?,javascript,function,Javascript,Function,我正在重写我的一个项目,这次我决定使用自调用函数来保存一些代码,但我变得非常不确定这是否可行,因为我不希望在page加载+运行init函数之前运行自调用函数 我想要的预期执行顺序如下: init: function() { //some code gets executed here createCalendar(2015); } addEventListnrs: (function() { //event listeners gets added here on el
init
函数之前运行自调用函数
我想要的预期执行顺序如下:
init: function() {
//some code gets executed here
createCalendar(2015);
}
addEventListnrs: (function() {
//event listeners gets added here on elements that gets created
//in the createCalendar function
})()
createCalendar: function(year) {
//creates elements that the addEventListnrs uses
}
window.onload = init;
问题是,这是我要得到的还是addEventListnrs函数会在init运行之前调用自身?假设您的标签是有效代码(即,您遗漏了一些代码)
init
由侦听器调用createCalendar
由init
你的生活应该这样安排:
(function(){}())
而不是(function(){})(
很容易测试这个。让每个函数都发出警报,看看哪个先出现等等。@theonlygusti:没关系。@theonlygusti:就像我说的,没关系。这两种方法都没有合理的建议,因为它们会有相同的结果。@theonlygusti哦?原因是什么?你的命令是正确的,但你的方式有点奇怪;IIFE会立即被调用(只要js加载),然后,当DOM就绪时,init就会运行,这会触发其他所有操作。