0

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

freethinker
  • 2,257
  • 4
  • 26
  • 49
  • 1
    It's impossible with the requirements posed. You either need to expose the function to everybody or you need to have a single script. There is no way to have a function both private and shared with a different script. – VLAZ Nov 13 '16 at 14:49
  • Possible duplicate of [javascript - accessing private member variables from prototype-defined functions](http://stackoverflow.com/questions/436120/javascript-accessing-private-member-variables-from-prototype-defined-functions) – yuvi Nov 13 '16 at 14:51

1 Answers1

5

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875