编辑:
一切都按我的预期进行。这只是调用模板方法时出错。我输错了 (),所以我尝试使用 template.method 而不是 template().method;
无论如何,如果有人愿意向我解释这是否是一个有效的设计模式,或者我是否应该采用不同的方式,我将非常感激。
<小时/>我阅读了有关模块模式的内容,并尝试在我的一些项目中实现它。问题是,在我看来,我扭曲得太多了。 我受到 Google Apps 脚本风格的启发,其中许多对象通过方法等返回其他对象,并且它们传递参数。
类似的东西
object.method(var).otherMethod();
我想要实现的是一种方法,该方法接收参数,将内部变量设置为该参数,然后返回一个具有使用该变量的方法的对象。这是不起作用的代码的缩小版本:
var H_UI =(function (window) {
var selectedTemplate,
compileTemplate = function(){},
parseTemplateFields = function(){};
//template subModule. Collect: collects the template fields and returns a JSON representation.
var template = function(templateString){
if(templateString) selectedTemplate = templateString;
return {
getHtml:function(){ return compileTemplate( parseTemplateFields( selectedTemplate ) ) } ,
collect:function(){
.. operating over selectedTemplate ...
return JSON.stringify(result)}
} };
return {
template:template
};
})(window);
<罢工> 如果我删除该行:
if(templateString) selectedTemplate = templateString;
并在返回对象的方法中将 selectedTemplate 替换为参数 templateString,它按预期工作。我知道我无法在返回的对象中创建 set() 方法并像这样使用它
H_UI.template().set(var)
但我觉得它很难看。无论如何,我认为我把事情搞砸了。
构建这个的最佳方法是什么?
罢工>
最佳答案
如果您希望每次调用 template()
时 H_UI.template()
创建一个新对象,您的解决方案将不起作用。因为变量 selectedTemplate
仅在调用立即函数时创建一次。
但是,如果您的意图是这样,您的解决方案就可以正常工作。 (变量 selectedTemplate
为所有对 template()
的调用所共享)。
但是如果您希望每次调用 template
都会创建一个新对象。请告诉我写下我的想法
关于javascript - 具有方法的模块模式 setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23712090/