Oleg Yudovich Oleg Yudovich - 25 days ago 9
Javascript Question

How to share same scope variables between different JS files

I have three script files. main.js, script1.js, script2.js.

The main.js just include that scripts into the document:

function IncludeJs(sFileName) {
document.writeln('<script type="text/javascript" src="' + sFileName + '"></script>');
}

IncludeJs("../script1.js");
IncludeJs("../script2.js");


The script1.js and script2.js code is under same namespace.

script1.js:

var sharedNamespace = sharedNamespace || {};

(function () {

"use strict";

function func1(){
....
}

}).apply(sharedNamespace );


script2.js:

var sharedNamespace = sharedNamespace || {};

(function () {

"use strict";

function func2(){
return func1();
}

}).apply(sharedNamespace );


The func2 is not working because func1 is undefined. How i can put script1.js and script2.js under same scope with shared variables?

The solution of
sharedNamespace.func1 = function(){}
, is worst for me, because i don't want to expose this function to client who use my library...

Answer

...i don't want to expose this function to client who use my library...

If you're going to have separate script files and you want them to define functions that call each other, you have no choice. It's impossible to have script1.js and script2.js share a common scope that isn't also accessible to other scripts on the page.

Instead, you'll probably want to have the separate files you use for development combined for deployment, because a single script can (of course) have private information. (Private unless the user edits the script, of course.)

So for instance, you might have something like this:

script1.js:

var internal = internal || {};
(function(i) {
    i.func1 = function func1() {
        // ...code here, possibly using i.func2()
    };
})(internal);

script2.js:

var internal = internal || {};
(function(i) {
    i.func2 = function func2() {
        // ...code here, possibly using i.func1()
    };
})(internal);

When doing development, you include them separately and so any code could use internal.func1. But then when doing your all-in-one-script build, you'd have it wrapped

(function() {
    // ...contents of script1.js here...
    // ...contents of script2.js here...
})();

Now, internal is private to the combined script.

That's off the top of my head; there are probably less cumbersome ways...