0

我对自动执行匿名函数的了解越多,我就越困惑:)

我的问题是:如果我使用 jQuery 的 document.ready 函数,我是否必须将整个应用程序逻辑放在该函数中?如果我在其他一些自动执行的匿名函数中有代码,我如何从 document.ready 调用中触发该代码?(没有在全局命名空间中放置任何变量?)

Document.ready 代码:

$(document).ready(function() {
    // how do I trigger another s.e.a.f. here?  
    var myApp = new App();
    myApp.initialize();
});

我在海洋中的应用逻辑:

(function(window){  
   function App(){
        this.initializeApp = function() {
              // we are initialised!
        }
   }
   // how do I prevent putting 'App' in the global space?
   window.App = App;
})(window);
4

2 回答 2

0

You can't.

The only way to communicate with a function outside your scope is to put an object somewhere in the global scope.

Instead, you should call $(document).ready() inside the IIFE, so that it will be able to access local variables via closures.

于 2013-01-20T13:45:32.067 回答
0

“如何从 document.ready 调用中触发该代码”

确保应用程序逻辑首先存在并且您使用您编写的函数名称。

(function(window){  
   function App(){
        this.initializeApp = function() {
              // we are initialised!
            console.log('initialised');
        }
   }
   window.App = App;
})(window);

$(function(){
    var myApp = new App();
    myApp.initializeApp();  // not myApp.initialize(); 
});

// how do I prevent putting 'App' in the global space?

这是一个单独的问题...

使用单独的实例。

jQuery(document).ready(function($){  
   function App(){
        this.initializeApp = function() {
              // we are initialised!
            console.log('initialised');
        }
   }
   // how do I prevent putting 'App' in the global space?

    var myApp = new App();
    myApp.initializeApp();    
});

jQuery(document).ready(function($){
    var myApp = new App(); // this will throw an error - it doesn't exist here
});
于 2013-01-20T13:55:19.880 回答