我遵循了 Stefanov 相当简单的模块模式。一切都很顺利,直到设计发生巨大变化:我必须生成模块的多个实例。
下面是一些简短的示例代码,展示了此模式的外观:
var MYAPP = MYAPP || {};
MYAPP = (function(){
// private properties
var connector = "connector.php",
my_list = [],
current_item = {},
beforeRender = false;
// private methods
_addCurrentItem = function(amount){
},
// public methods
add = function(amount){
amount += 5;
_addCurrentItem(amount);
}
// public API
return {
add: add
};
}());
仅使用 MYAPP
的一个实例时,一切都很好。但现在我需要更多实例,并发现我无法以这种方式实例化我的模块。 var my_instance = new MYAPP;
不起作用,因为没有构造函数。
使我的模块模式可实例化的最快、最好的方法是什么?
感谢您的帮助和建议!
最佳答案
怎么样:
- 删除自调用
- 保存到不同的变量(例如
App
) - 单独实例化
像这样:
var MYAPP = MYAPP || {};
var App = function(){
// private properties
var connector = "connector.php",
my_list = [],
current_item = {},
beforeRender = false;
// private methods
_addCurrentItem = function(amount){
},
// public methods
add = function(amount){
amount += 5;
_addCurrentItem(amount);
}
// public API
return {
add: add
};
};
MYAPP = new App();
MYOTHERAPP = new App();
关于JavaScript:Stefanov 模块模式的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36065052/