信息

我正在尝试建立一个站点,在其中可以包含某些文件,并使用不同的方法将其附加到全局变量中,这些方法将很容易添加到该对象中。意味着我只需要包含文件,该页面现在就可以访问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函数之前运行,则它将不存在。初始化无法运行到所有“附加组件”都已加载。

注意:您的第二个没有(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();


jsFiddle of above code

运行此命令时,您会看到由于未加载bar,因此首次调用该init将会失败。自从添加该方法以来,第二次它将起作用。因此,如果init依赖于已加载的“模块”,则需要知道它们何时加载才能调用init方法。

10-05 20:48
查看更多