简体   繁体   中英

Full break out javascript from child function

Simple question, I guess...

function foo1() {
    foo2();
    // should not hit this line
}
function foo2() {
    foo3();
    // should not hit this line
}
function foo3() {
   if(someCondition)
      // should not hit this line
}

if in foo3(), if I use simple return, it will continue execution in foo2() and foo3().

I understand it is possible tocheck for return value and so on, I am just wondering if it is possible to exit completely from foo3()?

To actually answer your question, sure, you could throw from foo3() :

 function foo1() { console.log(1) foo2() console.log("Never hits") } function foo2() { console.log(2) foo3(3) console.log("Never hits") } function foo3() { if (true) throw "Breakout" } try { foo1() } catch(e) { console.log(e) }

This is part of the reason exceptions bubble. There may be reasons for aborting an execution in this manner, but you may wish to consider alternatives.

But you probably don't want to do that as this is a very smelly architecture, but you already know the more idiomatic alternative is to check returns.

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