简体   繁体   English

从子函数中完全突破 javascript

[英]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().如果在 foo3() 中,如果我使用简单返回,它将继续在 foo2() 和 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()?我知道可以检查返回值等等,我只是想知道是否可以从 foo3() 完全退出?

To actually answer your question, sure, you could throw from foo3() :要真正回答您的问题,当然,您可以从foo3() throw

 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. 但是您 可能不想这样做,因为这是一个非常臭的架构,但您已经知道更惯用的替代方法是检查回报。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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