我一直在使用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
};
}
我正在转移到Revealing Prototype Pattern以获得一些内存使用改进,因此我可以为对象修饰另一个函数。如何将其保存在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
};
}());
答案 0 :(得分: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();
答案 1 :(得分:1)
var myProject = myProject || {}; ^^^
您在此处使用var
statement来声明全局myProject
变量(如果尚未声明),以便它不会抛出Undefined variable
个异常。 (如果它现在具有值,则将其初始化为空对象)
var myProject.models= myProject.models || {};
在这里,您要从上面为对象分配models
属性。 var
关键字在这里不合适;删除它,它会工作。
使用myProject.models.MyModel = …
,您在上方代码段中执行了正确的操作,而在第二个代码段中执行错误;我不确定你试图使用哪个。揭示原型模式应如下所示:
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;
})();