I have two js
file in my html
page . If the first one begins with :
(function($){
..
..
}(jQuery));
can I insert a var
into function($,varname)
, return
it's value and use it in the other file?
I have two js
file in my html
page . If the first one begins with :
(function($){
..
..
}(jQuery));
can I insert a var
into function($,varname)
, return
it's value and use it in the other file?
-
2
not
return
, but you can assign it as a property ofwindow
. – John Dvorak Commented Mar 4, 2013 at 12:16
3 Answers
Reset to default 3You need a global variable for this. You can do this in one of a few ways. Let's assume we need to send the value "Bacon" to the other script.
(function($){
window.myScriptsExports = "Bacon";
}(jQuery));
// OR
var myScriptsExports = (function($){
// other code
return "Bacon";
// NO other code
}(jQuery));
// OR (not really remended)
(function($){
// other code
$.myScriptsExports = "Bacon";
// other code
}(jQuery));
You can improve the code by using global namespace which goes like:
(function($,global){
var _obj = {};
_obj.property1 = 'Property1';
_obj.function1 = function() { console.log('Function 1');};
global.myObject = _obj;
}(jQuery,window));
//accessing
window.myObject.property1
//or
window.myObject.function1()
Supposing your function is synchrone, you may set a global function :
(function($){
..
var myvar = 666;
window.getMyVar = function() {
return myvar;
};
..
}(jQuery));
and you can use it from the other function if the second file is imported after this one :
(function($){
..
var myprevisouslysetvar = window.getMyVar();
..
}(jQuery));
Note that the files doesn't matter in javascript : your page would work the same (apart details if you have "use strict") with both files concatenated.