Reputation: 11175
I want to organize my JavaScript so I thought I would make a functions JS
file. Is there anyway I can call the functions from functions.js
from global.js
?
EDIT
functions.js:
var get_selects;
get_selects = {
getLanguages: function() {
}
}
global.js:
get_selects.getLangueges();
Upvotes: 1
Views: 388
Reputation: 80128
Yes, functions defined at the top level are automatically available in the global scope (window
in a browser), and this is typically not desirable.
Another approach that would mitigate this is to group your functions into a single object so you aren't polluting the global scope with a whole bunch of unrelated functions.
var utils;
utils = {
toast: function(message) {
alert("Notification: " + message);
},
sum: function(a, b){ return a + b; }
}
utils.toast('Email sent');
utils.sum(1, 2);
Upvotes: 5
Reputation: 1
From the moment you include a JS in the HTML file, all the functions become available. So, if you make like this, it will work:
<script type="text/javascript" src="functions.js"></script>
<script type="text/javascript" src="global.js"></script>
But (as soon as I know), you must include "functions.js" first. Otherwise, "global.js" will not be able to find the calls. You can also make a little function inside "global.js" to include "functions.js" on the fly, like this:
function include(js_path){
//By Fabrício Magri e Micox
//http://elmicox.blogspot.com/2006/12/include-em-javascript.html
var new= document.createElement('script');
new.setAttribute('type', 'text/javascript');
new.setAttribute('src', js_path);
document.getElementsByTagName('head')[0].appendChild(new);
}
Than, on the beginning of your "global.js" you call this function to include the contents of "functions.js" on the section as soon as the browser requests "global.js"
Upvotes: 0
Reputation: 1045
simply call it like anyother functions
yourFunctionName(yourFunctionParams);
be aware, you need to include your functions.js BEFORE your global.js, else it won't see your functions.
Upvotes: 0
Reputation: 17451
All .js files load top level functions into the global namespace. So, yes.
Upvotes: 0
Reputation: 47776
If both scripts have been included in the same HTML file, sure, it will work out of the box. Best way to know is to try it.
Upvotes: 0