Over a million developers have joined DZone.

Design Patterns with JavaScript Part I

DZone's Guide to

Design Patterns with JavaScript Part I

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

This post will be rehashing some ideas from two years ago when I did a previous Design Patterns series with other langauges. I have read on "23 Design Patterns mentioned by the GoF".  In that book, I was mainly concerned with Java and C#. But now I will looking to those same patterns from a JavaScript perspective. For those who don't know, a design pattern is a reusable software solution to a specific type of problem that occurs frequently when developing software. (If you're not familiar with JS, read one of my previous posts about JavaScript).

Types of Design Patterns

Design patterns are generally grouped into a few categories and I will cover the most important and recently used pattern types in my day to day development.
  • Creational patterns - Mainly concerned with ways to create objects or classes. Important in large applications where we have to control the object creation process.
  • Structural design patterns - Focuses on ways to manage relationships between objects, and therefore, helps in scaling the application. A key aspect of this patterns is that it makes loosely coupled components in an application.
  • Behavioral patterns – Deals with communication between objects.
Once we have a solid and firm grasp of design patterns and the specific problems they address, it becomes much easier to integrate them into our application architectures and pick the most approprate ones.
This post will cover ‘creational patterns’ with some samples

Creational patterns

  • Abstract Factory - Creates an instance of several families of classes
  • Constructor Pattern - All methods and properties of the object can be added in the constructor at creation level
  • Builder - Separates object construction from its representation
  • Factory Method - Creates an instance of several derived classes
  • Object Pool - Avoids expensive acquisition and release of resources by recycling objects that are no longer in use
  • Prototype - A fully initialized instance to be copied or cloned
  • Singleton - A class of which only a single instance can exist
Next, we'll look at the basics about JavaScript regarding object creational and behavioral patterns
There are three ways for creating new objects in JavaScript.

//1st way
var newObject = {};

//2nd way
var newObject = Object.create( null );

//3rd way
var newObject = new Object();

There are four ways in which keys and values can be assigned to an object: (1 and 2 are ECMAScript 3-compatible approaches and 3 and 4 are ECMAScript 5-only compatible approaches) Some sample code is at the bottom of the article. [1]
  1. Dot syntax
  2. Square bracket syntax
  3. Object.defineProperty
  4. Object.defineProperties

//1 way
newObject.someKey = "some value";
var key = newObject.someKey;

//2nd way
// Set properties
newObject["someKey"] = "some value";
// Get properties
var key = newObject["someKey"];

//3rd way
Object.defineProperty( newObject, "someKey", {
    value: "some value",
    writable: true,
    enumerable: true,
    configurable: true

//simple way
var defineProp = function ( obj, key, value ){
  config.value = value;
  Object.defineProperty( obj, key, config );

// To use, we then create a new empty "car" object
var myCar= Object.create( null );

// Populate the object with properties
defineProp( myCar, "brand",  "Toyota" );
defineProp( myCar, "year", "2009" );
defineProp( myCar, "bandnew", true );

//4th way 
Object.defineProperties( newObject, {

  "firstKey": { 
    value: "some vlaue", 
    writable: true 
  "secondrKey": { 
    value: "second value",
    writable: false 

//3 and 4 can be used any 1,2 getter mthod to get values

Here's my screenshot of the 4th one,
In the sample I am showing writable true and false acting in an object. (It is a bit simple, but it's a good value to know)

Constructor Pattern

Basic Constructors::
Object constructors are used to create specific types of objects. Constructors can be used to set the values of member properties and methods when the object is first created. The object is declared solely by its constructor. There's another sample gist at the end of the article. [2]
function Car(config) {
    this.name = config.name;
    this.engineSize = config.engineSize;
    this.toString = function () {
    return this.name + " has engine of " + this.engineSize + "cc";

    this.start = function () {
    return this.name + " start engine";


// create new instances of the car
var vitz = new Car({name:"Vitz", engineSize: 1000});
var prius = new Car( {name: "Prius", engineSize: 1800});

//now try our cars that is created
vitz.toString(); // --> Vitz has engine of 1000cc
prius.toString();  //--> Prius has engine of 1800cc
vitz.start(); //-->  Vitz start engine

Where is screen shoot I am try 4th one,
Constructors with Prototypes::
Functions in JavaScript have a property called a prototype. When we call a JavaScript constructor to create an object, all the properties of the constructor's prototype are then made available to the new object. In this fashion, multiple Car objects can be created that access the same prototype.

Car.prototype.stop = function () {
  return this.name + " stop engine";


Every JavaScript object has an internal property called Prototype. The true prototype of an object is held by the [[Prototype]] internal property. If you look up a property via obj.propName or obj['propName'] and the object does not have such a property, it can be checked via obj.hasOwnProperty('propName')

Above, a single instance of stop() will now be shared between all of the Car objects.
Later I will continue this tutorial series by covering a lot of patterns that I have written about previously.

[1] sample code in Gist:: https://gist.github.com/Madhuka/7497044

[2] constructor pattern sample :: https://gist.github.com/Madhuka/7497681

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}