信息
我正在尝试构建一个站点,在该站点中我可以包含某些文件并使用不同的方法附加到我的全局变量,这些方法可以轻松添加到对象中。这意味着我只需要包含该文件,此页面现在就可以访问 hutber 对象中的所有内容。
核心 hutber.js
var hutber = {};
(function ($) {
"use strict"; //For good development standards :)
hutber.init = function(){
};
hutber.init();
})(jQuery);
额外位 hutber.form.js
(function ($) {
"use strict"; //For good development standards :)
hutber.form = {
}
});
问题
我知道 hutber
将无法访问 hutber.form
,因为它位于闭包内。因此,如果不将这些从自执行函数中取出,我如何才能让 hutber
访问 hutber.form
呢?
或者这只是完全错误的解决方法?
最佳答案
不,它可以访问 hutber.form
,因为 hutber
是全局的,但问题是时间。
如果 init() 在执行 hutber.form
函数之前运行,则它将不存在。 init 无法运行到所有“附加组件”都加载完毕。
旁注:您的第二个将不会运行,因为它没有 (jQuery);
。
(function ($) {
"use strict"; //For good development standards :)
hutber.form = {
}
}); <-- missing (jQuery); so it is not going to do anything
运行一个小演示看看会发生什么。
var myObj = {};
(function(){
myObj.init = function(){
alert("init");
try{ //will fail since bar has not loaded yet
myObj.bar();
} catch(e){ alert("failed calling bar"); }
};
//call init before bar is loaded
myObj.init();
})();
(function(){
myObj.bar = function(){
alert("bar");
};
})();
//call init after bar has been loaded
myObj.init();
当您运行此命令时,您将看到 init 第一次调用时会失败,因为 bar 尚未加载。添加方法后第二次就可以了。因此,如果 init 依赖于加载的“模块”,则它需要知道它们何时加载才能调用 init 方法。
关于javascript - 自执行的匿名函数和闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14408527/