简体   繁体   中英

Can we use function as a return statement in javascript?

Well, is it possible to use function as return statement in outer function?

I want to use something like this:

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);
}

So, the function above should only calculate "a + b" but don't show it result because "returnFunction" should play a role of native "return" statement in "calculateFunction".

I know that I can always do something like this:

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

But my point is to actually simulate "return", replace it.

So, if it possible, what the "magic code" then?

The only way I can imagine something like that is if you 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
}

But then you would have to always use try , catch :

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

This is definitely not something nice to do. You should probably re-think your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM