【问题标题】:Can we use function as a return statement in javascript?我们可以在javascript中使用函数作为返回语句吗?
【发布时间】:2016-05-06 01:40:50
【问题描述】:

那么,是否可以在外部函数中使用函数作为返回语句?

我想用这样的东西:

function returnFunction(){
    // some magic (unknown for me) code here
}

// and here is just usual function
function calculateFunction(a,b){
    var result = a + b;
    returnFunction();
    showResult(result);
}

所以,上面的函数应该只计算“a + b”而不显示结果,因为“returnFunction”应该在“calculateFunction”中起到原生“return”语句的作用。

我知道我总是可以这样做:

function calculateFunction(a,b){
    var result = a + b;
    if( needReturnFunction() ) return;
    showResult(result); // won't run if above true
}

但我的意思是实际模拟“返回”,替换它。

那么,如果可能的话,那么“魔法密码”是什么?

【问题讨论】:

  • 您可以在return 语句中使用函数调用作为表达式的一部分,否则您的问题是无意义的。
  • 我不知道你想问什么。您如何描述您的实际问题,然后我们解决?
  • a throw new Error() 所做的事情与您所描述的相似。当然,你需要在某个地方抓住它,否则它会一直冒泡。
  • 未显示:return 可以返回 any 值,但必须在给定函数中使用 return(关键字)才能返回 a i> 价值。 (异常不返回值,尽管它们确实沿着调用堆栈流动并且可以被捕获。)
  • 没有可用的代码注入或宏系统。 returnFunction() 将无法直接影响调用者的流程,除非如您所见,调用者使用其返回值。也不能读取调用者环境的局部变量。

标签: javascript return


【解决方案1】:

我能想到的唯一方法就是如果你 throw

function returnFunction(){
    if (shouldReturn) throw 'return';
}

// and here is just usual function
function calculateFunction(a,b){
    var result = a + b;
    returnFunction();
    showResult(result); // won't run if above throws
}

但是你必须始终使用trycatch

try {
  calculateFunction(a, b);
}
catch (err) {
  // if error thrown is 'return' then ignore
  if (err !== 'return') throw err;
}

绝对不是好做的事。您可能应该重新考虑您的代码。

【讨论】:

  • 好吧,如果抛出异常是“唯一的方法”,那么最好总是使用像 if( needReturnFunction() ) return; 这样的 if 语句,而不是总是捕获“错误”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
  • 2015-12-05
  • 2015-11-07
  • 1970-01-01
  • 2016-07-26
  • 2022-01-17
相关资源
最近更新 更多