Create jquery functions in external files

I would like to create a js file with functions and call them in an other file like that :

utilities.myfunction();

How can I do this ? It should seem like that :

utilities.js :

$(document).ready(function(){
  // unknow syntaxe ...
});

main.js :

$(document).ready(function(){
    var something = utilities.myfunction();
});

index.html :

<script  src="utilities.js" type="text/javascript"></script>
<script  src="main.js" type="text/javascript"></script>

thanks in advance

1 Answers
  1. One way to accomplish what you're trying, is to create a namespace (an object in the global scope) and attach your function to that, for example like this:

    (function () {
    
        // Initialize namespace 'utilities' (or use existing one if present)
        window.utilities = window.utilities || {};
    
        // Add function 'myFunction' to the namespace
        utilities.myFunction = function () { ... };
    
    })();
    

    You can now use the function in a script later like this:

    var something = utilities.myFunction();
    
    tobi2013-10-09 10:26:42
Related Articles
You Might Also Like