Javascript: 在匿名函数中访问函数

Javascript: Accessing functions within Anonymous function

Using jQuery as suggested by Wordpress,我将我的代码包装在一个匿名函数中,这样 jQuery 就不会与其他 javascript 库冲突:

(function($) {

    // Inside of this function, $() will work as an alias for jQuery()
    // and other libraries also using $ will not be accessible under this shortcut

})(jQuery);

问题是我想将我的代码分成两个文件:1) main.js 和 2) utility.js。

主程序(main.js)如何调用另一个文件(utility.js)中的函数,当两者都被封装时?

utility.js

(function($) { 

function doSomething() {
    /* code here */
}

})(jQuery);

main.js

(function($) { 

$(document).ready(function(){
    doSomething();
}

})(jQuery);

谢谢

你可以使用return一个对象出来这个utility.js:

(function($, win) {
  win.util = function(){
    this.doSomething = function() {
      $('pre').append('util.js');
    }
  };
})(jQuery, window);

(function($, $U) { // <----referred it with $U

  $(document).ready(function() {
    $U.doSomething();
  });

})(jQuery, new util()); //<----pass the util object here.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>


实际上我喜欢在 OOJS 中使用它的方式。尝试创建一个构造函数并传递一个新对象。

最简单的解决方案是将 utility.js 中的所有函数分配给某个全局对象。假设您的代码在浏览器中工作,您可以这样做:

utility.js

(function($, context) { 

context.Utility = {
    doSomething: function() {
        /* code here */
    }
};

})(jQuery, window);

main.js

(function($, Utility) { 

$(document).ready(function(){
    Utility.doSomething();
}

})(jQuery, Utility);

更通用的解决方案是使用异步模块加载(http://requirejs.org/) or a tool like JSPM 来管理应用程序中的模块。