除了异常之外,是否可以在 JavaScript 中实现非本地返回?
非本地返回可以在 JavaScript 中实现吗?这样您就可以编写如下内容:
function some_function() {
function some_other_function(value) {
non-local-return true;
}
some_other_function();
return false;
}
true === some_function();
那么,some_function 将返回 true 吗?
Can non-local-returns be implemented in JavaScript, so that you could write something like:
function some_function() {
function some_other_function(value) {
non-local-return true;
}
some_other_function();
return false;
}
true === some_function();
where some_function would return true, then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
很简单,不。
(类似的问题在这里: let-a-function-return-the -超级功能)
Quite simply, no.
(similar question here: let-a-function-return-the-super-function)
模拟非本地返回的标准方法是使用异常:
boundary
将界定可以发生非本地返回的范围,而nonLocalReturn
将简单地包装在一个奇特的对象中增加“返回”值,然后抛出
它。您可以(理论上)使用它来实现类似于
findFirst
和forEach
: 的功能,这样
就能找到
42
。您的具体示例将变得
显然,尽管正确,但这与好的或有用的东西无关。请不要在任何实际代码中使用它。
The standard way to simulate non-local returns is to use exceptions:
The
boundary
would delimit a scope in which the non-local return can occur, and thenonLocalReturn
would simply wrap up the "returned" value in a fancy object, andthrow
it.You could (theoretically) use it to implement something like
findFirst
withforEach
:so that
would find the
42
.Your specific example would become
Obviously, despite being true, this has nothing to do with what's good or useful. Please don't use it in any real code.