0

I have been learning about encapsulation in Javascript with the module pattern. I want to give access to specific js files. From what I understand, it is only possible to restrict access to everything and give access to everything, is this correct?

smiley.js

(function(exports){
    function smiley(string){
        return string + ' :)';
    };
    exports.smiley = smiley;
})(this);

play.js

smiley('Hello');

Given an HTML file that includes smiley.js and play.js.

<script src='smiley.js'></script>
<script src='play.js'></script>

Is it possible to have another js file that does not have access to smiley.js but is also included in the HTML file?

Is there only global (window) scope and private scope or can I specify a scope for different files?

  • The browser only has two scopes - global and functional. If you encapsulate something in a module, it exists in a functional scope. At best, you can create something that manages those, creates the modules you want and then passes them to other things that need them (inversion of Control) but it's usually not needed. – VLAZ May 01 '18 at 12:11

1 Answers1

0

If I understand your question correctly, I would say:

const Script1 = (function () {
    // Encapsulate the logic.
    const Logic = {
        sayHi () {
            alert('Script1 says hi!');
        },
        shutUp () {
            alert('Shut up!');
        }
    };

    // Public attributes.
    return {
        sayHi () {
            Logic.sayHi();
        }
    }
})();

document.addEventListener('DOMContentLoaded', function () {
    Script1.sayHi(); // Will successfully work.
    // Script1.shutUp(); -> Will say "Script1.shutUp is not a function".
});

Basically the idea is simple. Inside the self-invoking function you declare an object, which will hold the functions and data fields. Then from the return statement of the self-invoking function you can make functions publicly available. This way you can keep the ones you want private - private, and the ones you want available - you can make available. The same applies for multiple JS scripts. Just each script declares it's own self-invoking function. Script1, Script2, etc...

Bilger Yahov
  • 377
  • 4
  • 14