Search code examples
javascriptprototyperevealing-module-pattern

How do you namespace objects in the Revealing Prototype Pattern?


I've been using the Revealing Module pattern and have several namespaces. Example:

// here's the namespace setup

var myProject= myProject|| {};
var myProject.models= myProject.models || {};

myProject.models.MyModel= function(){
   var someMethod = function(){
     // do something
   };
   return{
      SomeMethod = someMethod
   };
}

I'm moving to the Revealing Prototype Pattern to gain some memory usage improvements and so I can decorate the object another function. How do I keep it in my myProject.models namespace? This gives my JavaScript errors:

var myProject.models.MyModel= function(){
   // properties here
};

myProject.models.MyModel.prototype = (function(){
   // methods here
    var someMethod = function(){
         // do something
    };
    return{
       SomeMethod = someMethod
    };
}());

Solution

  • You have various syntax errors.

    myProject = window.myProject|| {};
    
    myProject.models = myProject.models || {};
    
    myProject.models.MyModel = (function () {
       //declare a constructor function
       function MyModel() {
       }
    
       //declare a function that will be publicly available on each MyModel instances
       MyModel.prototype.someFunction = function () {
           //call the private function from within the public one
           //note: you have to be careful here since the context object (this) will be
           //window inside somePrivateFunction
           somePrivateFunction();
    
           //call the private function and set the context object to the current model instance
           //somePrivateFunction.call(this);           
       };
    
       //declare a private function
       function somePrivateFunction() {
       }
    
       return MyModel; //return the model constructor
    })();
    

    Now you can use your model like:

    var m = new myProject.models.MyModel();
    m.someFunction();