Module Pattern in Javascript

this demo shows how to implement module pattern in javascript

JavaScript

//this demo shows how to implement module pattern in javascript
//1. use iffe: define a function and immediately calls itself. assign the iffe to some global variable.
//2. return an object in which define the public methods.
var m = (
   function(){
          var priv = function(){
              return "123-45-6789"; //in reality, get ssn from db for example.
          };

          var myObj = {
              getLastSsnLast4: function(){
                  var s = priv();
                  return s.slice(-4);
              }
          };
       
       return myObj;
   }
)();

var ssn = m.getLastSsnLast4();
console.log(ssn);
console.log(m);

//var fail = m.priv(); // this fails because m.priv isn't a method from the returned object.
//console.log("fail=", fail); 

//below: how to extend m:
var m2 = (function(module){
    module.ext = function(){
      console.log("ext of m added in m2");
    }
    
    return module;
})(m);

console.log(m2);
console.log(m);

m.ext();
m2.ext();