JavaScript: Design Patterns 02 – Object Literal Pattern

Object Literal Pattern

The most basic approach to dealing with the pollution of the global scope
is to use a simple object literal to wrap a custom library.

Script One
var myLibrary = {
name: 'My super duper library',
say: function(){ return `This entire object will be shadowed...`; }
Script Two
var myLibrary = 'This is not even a library, it\'s a string. Boy are you hosed!';

NOTE: only applicable when using 'var' to create variables.
When using 'let', JavaScript will throw an error that the variable name has
already been taken. This includes the case where one of the variables was created
using 'var' and the other was created using 'let', JS will still throw an error.

Custom Name-Spaced Pattern

Uses object literal pattern

Although this may protect the variables, functions, and objects within your
custom library, there is still the issue that someone else may use the same
variable name for an object in their script as you used for the name of your
library's object wrapper.

To overcome this issue, it is standard practice to follow a common Java name-spacing
technique, use a registered domain name you own as your namespace.

Domain Namespace
// Build the domain structure using object literals
// checking to make sure those objects do not already exist
var com = com || {};
com.memorytin = com.memorytin || {};
com.memorytin.myLibrary = com.memorytin.myLibrary || {
name: 'My super duper library',
say: function(){ return `This entire object will be shadowed...`; }

Note: the above only works if you are using ‘var’ to create the initial
namespace object. If you use ‘let’, the browser will throw an error due to the
fact that you are using ‘com’ on the right side of the assignment operator and
it has not yet been instantiated.

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s