2

我一直在使用 Revealing Module 模式并且有几个命名空间。例子:

// 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
   };
}

我正在转向显示原型模式以获得一些内存使用改进,因此我可以将对象装饰为另一个功能。如何将其保存在 myProject.models 命名空间中?这给了我的 JavaScript 错误:

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

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

2 回答 2

4

您有各种语法错误。

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

现在您可以使用您的模型,例如:

var m = new myProject.models.MyModel();
m.someFunction();
于 2013-04-09T19:34:34.053 回答
1
于 2013-04-09T19:36:15.890 回答