Showing posts with label prototype pattern. Show all posts
Showing posts with label prototype pattern. Show all posts

Friday, 30 August 2019

Object creation pattern in JavaScript


Following are the few main JavaScript object creation patterns:
  1. Factory Pattern 
  2. Constructor Pattern 
  3. Prototype Pattern 

1. Factory Pattern:

var carFactory = function(name, model, type){
 var obj = {};
 obj.name=name;
 obj.model=model;
 obj.type=type;
 
 obj.showCarDetails = function(){
  console.log("Name: "+ this.name);
  console.log("Model: "+ this.model);
  console.log("Type: "+ this.type);
 }
 return obj;
}

var car1 = carFactory('BMW','X5','SUV');
var car2 = carFactory('BMW','A6','Sedan');

car1.showCarDetails();
car2.showCarDetails();

  • It is similar to a regular function only difference is that it would need to return a new instance of some object to be considered as "Factory" function.
  • Ex. In above example we have created a new obj inside carFactory function and we are assigning the values (name,model,type) which we are passing to that object as a properties of it.
  • Factory function doesn't use the "new" keyword unlike Constructor function.
  • The problem with Factory function is that we cannot check whether the given object is created by certain factory. Ex. car instanceof carFactory // Return false

2. Constructor Pattern:


var CarConstructor = function(name, model, type){
 
 this.name=name;
 this.model=model;
 this.type=type;
 
 this.showCarDetails = function(){
  console.log("Name: "+ this.name);
  console.log("Model: "+ this.model);
  console.log("Type: "+ this.type);
 }
}

var car1 = new CarConstructor('BMW','X5','SUV');
var car2 = new CarConstructor('BMW','A6','Sedan');

car1.showCarDetails();
car2.showCarDetails();
  • Here since constructor pattern not returning any object we have to use "new" keyword to create object of it.
  • No need to return any as it'll implicitly return new object.
  • So every time we create new object from CarConstructor function it'll create new instance of it.
  • The functions execution context (this) will be set a new object.
  • We can check whether the give object is created by constructor 
  • i.e. car1 instanceof CarConstructor // return true

3. Prototype Pattern:


var carProto = function(){};

carProto.name="";
carProto.model="";
carProto.type="";
carProto.prototype.showCarDetails = function(){
  console.log("Name: "+ this.name);
  console.log("Model: "+ this.model);
  console.log("Type: "+ this.type);
}

var car1 = new carProto();

car1.name="Audi";
car1.model="A6";
car1.type="Sedan";

car1.showCarDetails();
  • In prototype pattern the advantage of it over constructor pattern is that the showCarDetails function is part of prototype space and not directly the part of car1 object.