我们正在使用 Angularjs 1x,我正在尝试重构 Angularjs 过滤器中的一些重复代码,但我在正确处理时遇到了问题。应该很简单。
我们有一个使用匿名自执行函数的过滤器的标准结构,类似于下面的代码。我在 for 循环中有一些带有重复代码的 if/else block ,我想创建一个可以消除重复的函数,但是,我似乎无法正确调用该函数。我该如何去做呢?
(function() {
//Named function
function abc(Input){
return function(value){
for(var i=0; i<3; i++){
if(w){
//Duplicate code here
} else if(x){
//Duplicate code here
} else if(y){
//Duplicate code here
} else if(z)
}
}
}
}
))();
这里有一些类似于重复代码的内容,并且每个 block 中都有完全相同的重复代码。我们有专门的标签处理服务。
if(Input[i].fpwInd === 'Y' && fpw.plan === 'State') {
fpwValues.push(weblService.returnLabel("yes", $rootScope.label));
break;
}else if(Input[i].fpwInd === 'N' && fpw.plan === 'Another State') {
fpwValues.push(weblService.returnLabel("no", $rootScope.label));
break;
}
这类似于最终有效的代码:
(function() {
var fwp = function(input, plan){
if(input == "value" && plan == "somevalue")
fpwValues.push(weblService.returnLabel("yes", $rootScope.label));
//rest of the if/else code here...
};
function abc(){
return function(value){
for(var i=0; i<3; i++){
if(w){
fwp(input, plan);
break;
} else if(x){
fwp(input, plan);
break;
} else if(y){
fwp(input, plan);
break;
} else if(z)
}
}
}
}
))();
最佳答案
以你的第二个例子为基础,你能做这样的事情吗?
如果您可以提供更多信息,那将是一个很大的帮助 - 为什么您不能正确调用该函数?你有什么错误吗?
(function() {
function getLabelStrForIndPlan(ind, plan) {
if (ind === 'Y' && plan === 'State') {
return 'yes';
}
else if (ind === 'N' && plan === 'Another State') {
return 'no';
}
}
function abc(Input){
return function(value){
for(var i=0; i<3; i++){
var fpwInd = Input[i].fpwInd;
var label = getLabelStrForIndPlan(fpwInd, fpw.plan);
if (label) {
fpwValues.push(weblService.returnLabel(label, $rootScope.label));
break;
}
}
}
}
})();
关于javascript - 如何在 Angularjs 中重构闭包中的重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37164361/