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);
谢谢
最佳答案
您可以使用此 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 方式使用它的方式。尝试创建一个构造函数并传递一个新对象。
关于Javascript:访问匿名函数中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34066635/