//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,...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.