自执行匿名函数和闭包

自执行匿名函数和闭包

本文介绍了自执行匿名函数和闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

信息

我试图构建一个网站,其中可以包含某些文件,并用不同的方法附加到我的全局变量只是轻松添加到对象。意思我只需要包含文件,这个页面现在可以访问hutber对象中的所有内容。

I am trying to build a site where I can include certain files and append to my global variable with different methods that will just add easily to the object. Meaning I only need to include the file and this page will now have access to everything in the hutber object.

core hutber.js p>

core hutber.js

var hutber = {};

(function ($) {
    "use strict"; //For good development standards :)

    hutber.init = function(){

    };
    hutber.init();
})(jQuery);

extra bits hutber.form.js

(function ($) {
    "use strict"; //For good development standards :)

    hutber.form = {

    }

});

问题

我知道 hutber 在闭包中不能访问 hutber.form 。因此,如果不使用这些从自执行函数,我如何获得 hutber 以访问 hutber.form
或者这是完全错误的方法来处理这个问题?

I am aware that the hutber will not have access to hutber.form as it within a closure. So without taking these out of selfexecuting functions how can I get hutber to have access to hutber.form?Or is this just the complete wrong way to approach this?

推荐答案

$ c> hutber.form ,因为 hutber 是全局的,但问题是时间安排。

No it will have access to hutber.form since hutber is global, but the problem is timing.

如果在执行 hutber.form 函数之前运行init(),它将不会存在。

If the init() runs before the hutber.form function is executed, it will not be there. The init can not run to all of the "add-ons" are loaded.

注意:你的第二个不会运行,因为它没有(jQuery);

A side note: your second one will not run since it has no (jQuery);.

(function ($) {
    "use strict"; //For good development standards :)

    hutber.form = {

    }

});  <-- missing  (jQuery); so it is not going to do anything

运行一个演示来看看会发生什么。

Run a little demo to see what happens.

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将失败第一次被调用,因为没有加载。第二次它将工作,因为该方法添加。因此,如果init依赖于加载的模块,它需要知道它们何时被加载以调用init方法。

When you run this, you will see that the init will fail the first time it is called since bar is not loaded. The second time it will work since the method is added. So if the init depends on the loaded "modules" it needs to know when they are loaded in order to call the init method.

这篇关于自执行匿名函数和闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:03