I am learning how to split my program across several javascript files that can be used in a browser – see my code below. I want to access the private variables and methods in MODULE
while inside MODULE.Submodule
(or vice versa). The obvious answer is that I should make those variables and methods public in MODULE
. Of course, if I make them public, then they are no longer private. When I had all my code in one single file, then the methods inside what is now MODULE.SubModule
could access all the private variables. I want to replicate that capability. That is, the private vars and methods in each module remain private to all the modules (or better, to specific modules) and only the public vars and methods from all modules are made public.
I've found several tutorials on how to achieve the splitting, but none seem to address this specific problem – accessing private vars and methods in one module while in another module in the browser.
// in module.js
let MODULE = (function () {
const privateVar = 'foo';
return {
publicVar: 'bar',
// should return foo -> works
publicMethod: function () { return privateVar; };
};
})();
// in module-submodule.js
MODULE = (function (my) {
const privateVar = 'baz';
my.SubModule = {
// should return baz -> works
publicMethod: function () { return privateVar },
// should return foo from parent MODULE -> DOES NOT work
superPublicMethod: function() { return my.privateVar}
}
return my;
})(MODULE || {});
console.log(MODULE.publicMethod()); // return 'foo'
console.log(MODULE.SubModule.publicMethod()); // returns 'baz'
console.log(MODULE.SubModule.superPublicMethod()); // returns 'undefined'