简体   繁体   中英

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:

(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

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.

The simplest solution is to assign all functions in utility.js to some global object. Assuming your code works in the browser you could do something like this:

utility.js

(function($, context) { 

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

})(jQuery, window);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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