Javascript Creational Design Patterns

Looking at Constructor and Modular Creational patterns in Javascript.

by Richard Lovell

JavaScript

//CREATIONAL DESIGN PATTERNS

//1. CONSTRUCTOR PATTERN

//a) BASIC CONSTRUCTOR

//class ("blueprint" for each object to be created)
function Car(model) {
    //properties (representing state)
    this.model = model;//setting the model in the "constructor"
    this.color = "silver";
    this.year = "2014";

    //method (representing behaviour)
    this.getInfo = function () {
        return this.model + " " + this.year;
    };
}

//Usage:

//creating a new instance of Car, passing in the "model"
var fiesta = new Car("Ford Fiesta");

//setting the year property 
fiesta.year = "2015";

//calling the method
console.log(fiesta.getInfo());

//Problems with this method:
//1. Inheritence is difficult.
//2. Methods are redefined for each object.


//Solution:

//b) CONSTRUCTOR WITH PROTOTYPE

function Car2(model, year, miles) {
    this.model = model;
    this.year = year;
    this.miles = miles;
}

//defining "toString" method for Car object's prototype object, which will
//be shared by all Car objects
Car2.prototype.toString = function () {
    return this.model + " has done " + this.miles + " miles";
};

// Usage:

var civic = new Car2("Honda Civic", 2009, 20000);
var mondeo = new Car2("Ford Mondeo", 2010, 5000);

console.log(civic.toString());
console.log(mondeo.toString());


//2. MODULAR PATTERN
//keeping units of code separated and organised

//a) OBJECT LITERAL

var bmw = {
    //properties
    model: "BMW 3 Series",
    year: "2015",
    miles: 10000,
    //method
    toString: function () {
        return this.model + " has done " + this.miles + " miles";
    }
};

console.log(bmw.toString());

//Problem: What happens if you there are other variables named "bmw" 
//(third-party or otherwise) in the same (global) scope?


//Solution:

//b) NAMESPACE USING A CLOSURE
//a self-contained (encapsulated) unit of code

//some variables to pass in
var model = "Nissan Maxima";
var year = "2005";
var miles = 100500;

// Global module
var car3 = (function (model, year,...