Controlling Global Scope Access
Utilizing the Module Patterns, we can control access to the Global Scope
in the following ways:
- Using Modules to make everything private
- Conditionally add elements to the Global Scope
- Send things from the Global Scope into your custom module
This is accomplished by wrapping the library with an IIFE and anonymous function
and pass everything the library needs to run into that IIFE for use. This removes
your library completely out of the Global Scope.
(function(window, document, $){ // IIFE will execute and return an object literal var myLibrary = (function(){ // Private scope as everything within the anonymous function is hidden // Private variables let _privateData = 'this is private stuff'; // Private functions function _doSomethingPrivate(){ console.log('Just did something private.'); } // Public API functions function doThis(){ console.log('This was done.'); } function doThat(){ console.log('That was done.'); doSomethingPrivate(); } // The returned object contains the public API to the library return { doThis, doThat } })(); // within this private scope, library api can be executed $(document).ready(function(){ myLibrary.doThis(); myLibrary.doThat(); }); /* within this private scope, the library api can be added to the window object so that it can be used externally.*/ if(!window.myLibrary) window.myLibrary = myLibrary; // passing in only the Global Scope objects we need for our library to function })(window, document, jQuery);
Published by