【发布时间】: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