简体   繁体   English

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

[英]Javascript: Accessing functions within Anonymous function

Using jQuery as suggested by Wordpress , I have wrapped my code in an anonymous function so that jQuery will not conflict with other javascript libraries: 按照Wordpress的建议使用jQuery ,我将代码包装在一个匿名函数中,以便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);

The problem is that I want to split my code into two files: 1) main.js and 2) utility.js. 问题是我想将我的代码分成两个文件:1)main.js和2)utility.js。

How can the main program (main.js) call functions within the other file (utility.js) when both are encapsulated? 将主程序(main.js)封装在一起后,如何在另一个文件(utility.js)中调用函数?

utility.js Utility.js

(function($) { 

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

})(jQuery);

main.js main.js

(function($) { 

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

})(jQuery);

Thanks 谢谢

You can use to return an object out of this utility.js : 您可以用来从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> 


Actually i like the way to use it in OOJS way. 实际上,我喜欢以OOJS方式使用它的方式。 Try creating a constructor and pass a new object. 尝试创建一个构造函数并传递一个新对象。

The simplest solution is to assign all functions in utility.js to some global object. 最简单的解决方案是将utility.js所有功能分配给某个全局对象。 Assuming your code works in the browser you could do something like this: 假设您的代码在浏览器中可以运行,您可以执行以下操作:

utility.js Utility.js

(function($, context) { 

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

})(jQuery, window);

main.js main.js

(function($, Utility) { 

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

})(jQuery, Utility);

A more general solution would be to use asynchronous module loading ( http://requirejs.org/ ) or a tool like JSPM to manage modules in your application. 一个更通用的解决方案是使用异步模块加载( http://requirejs.org/ )或类似JSPM的工具来管理应用程序中的模块。

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

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