JavaScript Object Creation Patterns Part 1

To continue the series on Object Oriented Patterns, here is the first entry covering JavaScript; focusing on Object Creation Patterns.

Namespace Pattern

JavaScript doesn’t support namespaces, however, to avoid naming collisions and reduce the number of global variables, namespaces can be emulated using the technique of creating a global object, and adding functionality and variables to it.

Below is an example of the pattern:

var ExampleLibrary = {
        sampleProperty: 'value'
        ,sampleFunction: function() {}
};

Sandbox Pattern

The Namespace Pattern above shows how to create a basic code structure. However, when using two versions of the same namespace on the same page, we end up with clashing variable names, bound to it. To address this issue, the Sandbox Pattern isolates the functionality and provides a “safe” environment for each module attached to a namespace. 

Instead of using a global object, the Sandbox Pattern requires a global object constructor, taking in an array of modules to be used, and a variable name to attach them to.

Sample Sandbox pattern implementation:

function Sandbox( modules, ns ) {
        // Attach each requested module, to the 'ns' object
        for ( var i = 0; i < modules.length; i++ ) {
                ns[modules[i]] = this[modules[i]];
        }
}

Sample usage:

   var application = {};
        Sandbox( [ 'dom', 'text' ], application );

Chaining pattern

To avoid splitting the code on multiple lines, or assigning return values to previous variables, the Chaining Pattern allows you to call multiple objects methods one after the other. Example below:

// Object implementing chaining functionality
function Example() {
        this.set = function( property, value ) { this[property] = value; return this; }

        return this;
}

// Example usage
var Instance = new Example();
Instance.set( 'property1', 1 ).set( 'property2', 2 );

The three patterns above, solve the issues of polluting the global variable namespace, allowing multiple versions of the same library on the same page and splitting the code on multiple lines. These, along with function usage patterns and member declaration patterns, provide the basis for the Module Pattern. Next entry will pave the way for presenting the Module Pattern.