javascript - 嵌套 "Return"以退出父函数?

标签 javascript angularjs

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

$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/

相关文章:

javascript - ajax调用时执行另一个函数的原因

javascript - 在 AngularJS 中使用 Coldfusion 查询结果集

javascript - 谷歌浏览器 : A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true

asp.net - 将 id 设置为 gridview 中的面板控件

javascript - 使用 Angular 从 *ngFor 中删除 *ngFor 中的项目

javascript - 更改自定义元素的原型(prototype)

javascript - jQuery表格搜索切表头

javascript - 在 AngularJS View 中使用 jQuery 插件

javascript - "Failed to instantiate module ' app ' due to" Angular 和平均堆栈

javascript - 如何使用可能包含空单元格的 JSON 数据填充表格 (AngularJS)