Dynamic Prototype Pattern

The Dynamic Prototype Pattern of declaring the object has advantages of constructors as well as of prototypes. Here the prototype is initialized inside the constructor only if needed. The data is encapsulated and makes code simpler.

The prototype is declared inside the constructor and it is executed only in need, i.e. first time the constructor is called. The changes done in prototype are reflected in all of its instances. If there are multiple properties and methods, if condition can be applied and checked for one method/property.

Example of a dynamic prototype pattern

In this example, the "created" is undefined before bookHouse object is created. Hence we get “undefined in main” as output first. When object is created with the new keyword, ”created” becomes true. So the block of code is executed only once. When "myLib" is created we do not go to the block of code.

Parasitic Constructor Pattern

In Parasitic Constructor Pattern method, constructor does the object creation and returns the object. This is similar to factory pattern except function is a constructor. We use this pattern to create object where constructor for the object cannot be created other than with this method. Example, adding a user defined function to the array and returning the object.

Example of a parasitic constructor pattern

 

›› go to examples ››