那么,是否可以在外部函数中使用函数作为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);
}
所以,上面的函数应该只计算" a + b"但是不要显示结果,因为" returnFunction"应该扮演本土的角色" return" " calculateFunction"。
中的陈述我知道我总能做到这样的事情:
function calculateFunction(a,b){
var result = a + b;
if( needReturnFunction() ) return;
showResult(result); // won't run if above true
}
但我的观点是实际模拟"返回",替换它。
所以,如果可能的话,"魔术代码"然后?
答案 0 :(得分: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
}
但是,您必须始终使用try
,catch
:
try {
calculateFunction(a, b);
}
catch (err) {
// if error thrown is 'return' then ignore
if (err !== 'return') throw err;
}
绝对不是一件好事。您可能应该重新考虑您的代码。