VSO*_*VSO 2 javascript angularjs
我的目标是检查一个条件并退出当前函数.但是,我更喜欢在我要退出的函数调用的另一个函数中执行此操作.一个简单的例子,它不调用单独的函数,只检查正文中的条件:
$scope.doStuff = function(){
if (something) {
return;
}
doSomething();
}
Run Code Online (Sandbox Code Playgroud)
以下部分可以......
if (something) {
return;
}
Run Code Online (Sandbox Code Playgroud)
...放在一个可以在doStuff()中使用的函数,就像这样?
$scope.doStuff = function(){
$scope.exitOnCondition();
doSomething();
}
$scope.exitOnCondition){
if (something) {
return;
}
}
Run Code Online (Sandbox Code Playgroud)
显然在我编写它的方式中,"return"将返回exitOnCondition函数,而不是doStuff.像往常一样,我不需要检查代码,只是一个通用的例子,这里的一切只是为了说明问题.
小智 5
有exitOnCondition返回一个布尔值,并调用它在if声明.
$scope.doStuff = function(){
if ($scope.exitOnCondition())
return;
doSomething();
}
$scope.exitOnCondition = function(){
if (something) {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
为了避免return在主要功能中,您可以稍微重组它,但if需要留下来.
$scope.doStuff = function(){
if (!$scope.exitOnCondition())
doSomething();
}
$scope.exitOnCondition = function(){
if (something) {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
注意!结果的否定.如果颠倒exitOnCondition()函数的含义,这可能会更清晰一些.
$scope.doStuff = function(){
if ($scope.passedCondition())
doSomething();
}
$scope.passedCondition = function(){
if (something) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1628 次 |
| 最近记录: |