Question

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
    };
}());
Was it helpful?

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();

OTHER TIPS

var myProject = myProject || {};
^^^

You are using a var statement here to declare the global myProject variable (if it hasn't been already), so that it will not throw Undefined variable exceptions. (Also you initialise it to an empty object if it had now value)

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

In here, you are assigning the models property to the object from above. The var keyword is out of place here; remove it and it will work.

With myProject.models.MyModel = … you did it right in the upper snippet and wrong in the second one; I'm not sure which you were trying to use. The revealing prototype pattern should look like this:

var myProject = myProject || {};
myProject.models = myProject.models || {};
myProject.models.MyModel = (function(){
    function MyModel() {
        // instance properties here
    }
    function someMethod(){
        // do something
    }
    MyModel.prototype.SomeMethod = someMethod;
    //                ^ lowercase that?
    return MyModel;
})();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top