我们可以在javascript中将函数用作返回语句吗?
那么,是否可以在外部函数中使用函数作为返回语句 我想用这样的东西:我们可以在javascript中将函数用作返回语句吗?,javascript,return,Javascript,Return,那么,是否可以在外部函数中使用函数作为返回语句 我想用这样的东西: 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); }
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);
}
function calculateFunction(a,b){
var result = a + b;
if( needReturnFunction() ) return;
showResult(result); // won't run if above true
}
因此,上面的函数应该只计算“a+b”,而不显示它的结果,因为“returnFunction”应该在“calculateFunction”中扮演本机“return”语句的角色
我知道我总是可以做这样的事情:
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);
}
function calculateFunction(a,b){
var result = a + b;
if( needReturnFunction() ) return;
showResult(result); // won't run if above true
}
但我的观点是要模拟“返回”,替换它
那么,如果可能的话,“魔法代码”是什么呢?我能想象的唯一方式就是你抛出
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
}
但是您必须始终使用try
,catch
:
try {
calculateFunction(a, b);
}
catch (err) {
// if error thrown is 'return' then ignore
if (err !== 'return') throw err;
}
这绝对不是一件好事。您可能应该重新思考您的代码。您可以在
return
语句中使用函数调用作为表达式的一部分,但在其他方面,您的问题是无意义的。我不知道您想问什么。你来描述一下你的实际问题,然后我们来解决它怎么样?一个抛出新错误()
做了一些与你描述的相似的事情。当然,您需要在某个地方捕获它,否则它会一直冒泡。如图所示:return
可以返回任何值,但必须在给定函数中使用return
(关键字)才能返回值。(异常不会返回值,尽管它们会沿着调用堆栈流动并被捕获。)没有代码注入或宏系统可用。returnFunction()
无法直接影响调用方的流,除非调用方使用其返回值。它也不能读取调用者环境的局部变量代码>而不是总是捕获“错误”