我的目标是检查条件并退出当前函数。但是,我更愿意在从我想退出的函数调用的另一个函数中执行此操作。不调用单独函数而只检查主体中的条件的简单示例:
$scope.doStuff = function(){
if (something) {
return;
}
doSomething();
}
下面的部分可以...
if (something) {
return;
}
...像这样放置在可以在 doStuff() 中使用的函数中?
$scope.doStuff = function(){
$scope.exitOnCondition();
doSomething();
}
$scope.exitOnCondition){
if (something) {
return;
}
}
很明显,按照我写的方式,“return”将从 exitOnCondition 函数返回,而不是 doStuff。和往常一样,我不需要检查代码,只是一个一般的例子,这里的一切只是为了说明问题。
最佳答案
让 exitOnCondition
返回一个 bool 值,并在 if
语句中调用它。
$scope.doStuff = function(){
if ($scope.exitOnCondition())
return;
doSomething();
}
$scope.exitOnCondition = function(){
if (something) {
return true;
}
}
为了避免 main 函数中的 return
,您可以对其进行一些重构,但需要保留 if
。
$scope.doStuff = function(){
if (!$scope.exitOnCondition())
doSomething();
}
$scope.exitOnCondition = function(){
if (something) {
return true;
}
}
注意 !
结果的否定。如果反转 exitOnCondition()
函数的含义,这可能会更清晰一些。
$scope.doStuff = function(){
if ($scope.passedCondition())
doSomething();
}
$scope.passedCondition = function(){
if (something) {
return false;
}
}
关于javascript - 嵌套 "Return"以退出父函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32869507/