Javascript 如何从这个函数中简化样板文件?
在我的qooxdoo应用程序中,我有4个按钮。登录、注销、注册和配置文件。每个按钮都有一个action类。这些类是从一个公共抽象类派生的。通过使用命令模式,每次单击按钮时,我都调用相应类的execute函数。函数如下所示Javascript 如何从这个函数中简化样板文件?,javascript,oop,qooxdoo,Javascript,Oop,Qooxdoo,在我的qooxdoo应用程序中,我有4个按钮。登录、注销、注册和配置文件。每个按钮都有一个action类。这些类是从一个公共抽象类派生的。通过使用命令模式,每次单击按钮时,我都调用相应类的execute函数。函数如下所示 execute: function() { var contentString = "login-form"; //do some generic stuff if (win.getContentString() ==
execute: function() {
var contentString = "login-form";
//do some generic stuff
if (win.getContentString() === contentString) {
//do some generic stuff
} else {
var content = new myapp.apps.userActions.SLoginForm();
//do some more generic stuff
}
}
execute函数必须在所有4个子类中实现,唯一需要更改的是变量content和contentString
我正在考虑使用一个工厂函数,每次都基于contentString变量返回适当的对象
execute:function(){
var contentString = "login-form";
this.doTheGenericStuff(contentString);
},
doTheGenericStuff: function(contentString){
//do the generic stuff
var content = this.getTheObject(contentString);
//do some more generic stuff
},
getTheObject: function(contentString){
switch(contentString){
case "login-form":
return new myapp.apps.userActions.SLoginForm();
break;
case "register-form":
return new myapp.apps.userActions.SRegisterForm();
break;
//etc
}
}
虽然这看起来还可以(还没有测试过),但我不太喜欢它,因为每次添加新操作时,我都必须更新factory函数。有没有比这更聪明的方法呢?可能是javascript的一些我不知道的特性?次要的一点,但是如果您已经有了
return
语句,那么您不需要为每个案例都有break
语句,因为这就足够存在开关了
您可以传递一个额外的参数,并使用它调用构造函数,使用括号表示法而不是点表示法
execute:function(){
var contentString = "login-form";
var objectType = "SLoginForm";
this.doTheGenericStuff(contentString, objectType);
},
doTheGenericStuff: function(contentString, objectType){
//do the generic stuff
var content = this.getTheObject(objectType);
//do some more generic stuff
},
getTheObject: function(objectType){
return new myapp.apps.userActions[objectType]();
}
我认为在这种情况下使用更合适
因此,在抽象类中,您有:
getMyContentString: function() { return "login-form"; //or any default value },
getMyContent: function() { return new myapp.apps.userActions.SLoginForm() },
execute: function() {
var contentString = getMyContentString(); // to be overridden
//do some generic stuff
if (win.getContentString() === contentString) {
//do some generic stuff
} else {
var content = getMyContent();
//do some more generic stuff
}
}
每个子对象只需要提供适当的getMyContentString()
和getMyContent()