// creational
function Person(fName,lName)
{
this.fName = fName;
this.lName = lName;
this.displayName = function() {
return this.fName+'---'+lName;
}
}
var p1 = new Person("Ram","Mohan");
console.log(p1.displayName());
console.dir(p1);
var p2 = new Person("Shyam","Mohan");
console.log(p2.displayName());
console.dir(p2);
// drawback : displayName fn is getting created for each Person Object
/***************Prototype********************************************/
/*Person.prototype.showFullName = function() { return this.fName+'***'+this.lName};
*/
Person.prototype = { showFullName1 : function () { return this.fName+'***'+this.lName},
showAlert : function() { alert("hi!");}
};
var p1 = new Person("RamP","Mohan");
//p1.showAlert();
console.log(p1.showFullName1());
console.dir(p1);
var p2 = new Person("ShyamP","Mohan");
console.log(p2.showFullName1());
console.dir(p2);
/*********** Factory pattern **************************/
//Creates objects on specific requirements / configurations
function carFactory(){
this.createCars = function(type)
{
var obj;
switch(type) {
case "suv" : obj = new SUV();break;
case "hatch": obj = new Hatch();break;
default: obj = new Sedan();break;
}
obj.type = type;
obj.getCarInfo = function(){
console.log(this.type + " type of car has mileage of "+ this.mileage + "km/h");
}
return obj;
}
}
function SUV() {
this.mileage = 12;
}
function Hatch() {
this.mileage = 24;
}
function Sedan() {
this.mileage = 18;
}
var car = new carFactory();
console.log(car);
var c1 = car.createCars("suv");
console.log(c1.getCarInfo());
var c2 = car.createCars("hatch");
console.log(c2.getCarInfo());
//******** Module pattern **********************//
// encapsulates a group of methods for common purpose
//, only interface exposed , implementation is private
// its lke exposing public api, use as a service
var EventService = function () {
return {
register : function(name){
console.log("Register for...
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.