使用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);问题是我想将我的代码分成两个文件: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);谢谢
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:
(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.
How can the main program (main.js) call functions within the other file (utility.js) when both are encapsulated?
utility.js
(function($) { function doSomething() { /* code here */ } })(jQuery);main.js
(function($) { $(document).ready(function(){ doSomething(); } })(jQuery);Thanks
最满意答案
您可以使用从该实用程序返回一个对象.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的方式来使用它。 尝试创建一个构造函数并传递一个新对象。
You can use to return an object out of this 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. Try creating a constructor and pass a new object.
更多推荐
发布评论