我一直在使用揭示模块模式并拥有多个命名空间。 示例:
// 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
};
}());
最佳答案
您有各种语法错误。
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();
关于javascript - 如何在揭示原型(prototype)模式中命名对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15910853/