-1

Module Pattern (or) Prototype Pattern

Use Case : I have to create multiple objects, but the base class is not get any derived class, I can use module pattern with common global functions instead with prototype.

for Example:

code 1: (module pattern)

var globals = {
   method1 : function(){
       console.log("global method"); 
   }
}
function closureModule(){
    obj = {};
    obj.commonMethod = globals.method1;
    function pvtMethod(){
        console.log("private");
    }
    obj.privateMethod = pvtMethod
    return obj;
}
var o1 = closureModule();
var o2 = closureModule();
.
.
.
.
var o100 = closureModule();

code 2 : (prototype pattern)

function base(key){
    this.KEY = key;
}

base.prototype.commonMethod = function(){
    console.log("common Method", this);
}

var o1 = new base("0");
var o2 = new base("1");
.
.
.
.
var o100 = new base("100");
Deepaklal
  • 1
  • 2
  • You can use a (revealing) module pattern both around factories and around constructors+prototypes. The modularisation is just better for code organisation, which approach you use at object creation is purely opinion-based. – Bergi Jun 14 '16 at 13:51
  • please share any link related to revealing module pattern with an example. – Deepaklal Jun 15 '16 at 15:28
  • You surely can hit that term in your [favourite search engine](https://stackoverflow.com/search?q=revealing+module+pattern), can't you? – Bergi Jun 15 '16 at 16:06

1 Answers1

0

The module pattern is most useful to enforce proper encapsulation by hiding away internal implementation details.

If you just want multiple instances of the same "class" to share a public function then using the prototype is the right approach.

plalx
  • 42,889
  • 6
  • 74
  • 90