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.

Read More

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

Related posts

2 comments

  1. 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.

  2. 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.

Comments are closed.