简体   繁体   English

从另一个函数返回一个自执行函数(IIFE)

[英]returning a self executing function (IIFE) from another function

(function($) {

    var foo = (function(){

        //some functions

    })();

    // I can access foo here
    var f = new foo();

})(jQuery);

// But obviously not here since it's in another scope

How do I return foo to the window scope, so that it can be accessed outside of the outer IIFE? 如何将foo返回窗口范围,以便可以在外部IIFE之外访问它? I've tried return foo; 我试过return foo; but it did not work. 但它没有用。

Simply set it as a window property: 只需将其设置为window属性:

(function($) {

    var foo = (function() {

        // some functions

    })();

    window.foo = foo;
//  ^^^^^^^^^^^^^^^^^

})(jQuery);

foo();

However, setting global objects as properties of the window object is typically looked down upon. 但是,通常会忽略将全局对象设置为window对象的属性。 Perhaps you can emulate this ability by managing your own custom "global" object. 也许您可以通过管理自己的自定义“全局”对象来模仿此功能。 For example: 例如:

var global = {};

(function($) {

    global.foo = (function() {

        // define

    })();

})(jQuery);

global.foo();

That way you won't have name clashes when dealing with a variety of scopes and objects. 这样,您在处理各种范围和对象时就不会发生名称冲突。

Using global properties is a express ticket to spaghetti code. 使用全局属性是通向意大利面条代码的明确证明。 Your whole application should live in as few elements in the global object as possible, ideally only one. 您的整个应用程序应位于全局对象中尽可能少的元素中,理想情况下应仅包含其中一个。

This is much more elegant and safe at the long term. 从长远来看,这将更加优雅和安全。

var MYAPP = {}; //declaring with var is not necessary here, but it's good to keep constant.

MYAPP = (function($, MYAPP) {

    var foo = (function(){

        //some functions

    })();

    // enrich your object
    MYAPP.foo = foo;
    return MYAPP;

})(jQuery, MYAPP);

And then you can use your "enriched" MYAPP object. 然后,您可以使用“丰富的” MYAPP对象。

MAYPP.foo();

A pattern similar to this is suggested by JavaScript's God: Douglas Crockford. JavaScript的上帝(Douglas Crockford)提出了类似的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM