嵌套"Return"退出父函数?



我的目标是检查一个条件并退出当前函数。然而,我更愿意在从我想退出的函数调用的另一个函数中执行此操作。简单的例子,不调用单独的函数,只检查body中的条件:

$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返回一个布尔值,并在if语句中调用它

$scope.doStuff = function(){
  if ($scope.exitOnCondition())
    return;
  doSomething();
}
$scope.exitOnCondition = function(){
      if (something) {  
        return true;
      }
}

为了避免return在main函数中,你可以稍微重组一下,但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;
      }
}

您可以让exitOnCondition返回一个值,您可以在父函数中检查。

$scope.exitOnCondition = function() {
  if (something) {
    return true;
  }
  // ...
  return false; // Could omit this entirely
};
$scope.doStuff = function() {
  if ($scope.exitOnCondition()) {
    return;
  }
  doSomething();
};

最新更新