I have heard lot about Javascript: Module Pattern. But most of those articles explain how to make static classes i.e when we don’t have to deal with instances and we want to share the object created modular pattern. Can some one explain me this pattern with constructor functions say this example:
function Shape(x, y) {
this.x= x;
this.y= y;
}
Shape.prototype.toString= function() {
return 'Shape at '+this.x+', '+this.y;
};
function Circle(x, y, r) {
Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords
this.r= r;
}
Circle.prototype= new Shape();
Circle.prototype.toString= function() {
return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r;
}
How do I convert it to modular pattern? and is there any benefit to use it in modular pattern way?
The benefit of using the module pattern is encapsulation.
Maybe this is what you want:
This, however, has no clear benefit. This allows you to create private variables, but you could do it with classic constructors too:
Or maybe you would like to encapsulate both Shape and Circle in a module. In this case you only have to return Shape and Circle from your module: