JavaScript: Design Patterns 05 – Controlling Global Scope Access

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.');

// The returned object contains the public API to the library
return {


// within this private scope, library api can be executed

/* 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

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#,, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s