简体   繁体   English

JavaScript function 调用子表达式可以是尾调用吗?

[英]Can JavaScript function call subexpressions be tail calls?

Consider the following return statement:考虑以下返回语句:

return f() || g();

The call f() obviously is not a tail call, because the function does not actually return if f() is falsy.调用f()显然不是尾调用,因为如果f()是虚假的,则 function 实际上不会返回。

What about the g() part though, is that a tail call?但是g()部分呢,那是尾调用吗? Or do I have to rewrite it like this:还是我必须像这样重写它:

const temp = f();
if (temp) return temp; else return g();

Yes, but it doesn't help in practice.是的,但在实践中没有帮助。

According to the standard , g() is in tail position:根据 标准g()在尾部 position 中:

LogicalORExpression: LogicalORExpression ||逻辑或表达式:逻辑或表达式 || LogicalANDExpression逻辑与表达式

Return HasCallInTailPosition of LogicalANDExpression with argument call.使用参数调用返回 LogicalANDExpression 的 HasCallInTailPosition。

However, most browsers don't support tail call elimination, and the Chromium team isn't working on it, so you can't rely on tail call elimination in practice no matter how you write your tail calls.但是,大多数浏览器不支持尾调用消除,Chromium 团队也没有在做这方面的工作,所以无论你如何编写你的尾调用,你都不能在实践中依赖尾调用消除。

Try it and see?试试看?

For some reason that didn't occur to me in my sleep-deprived state:D出于某种原因,在我睡眠不足的情况下,我没有想到 state:D

function f() {
    return Math.random() > 1 || f();
}

f()

Node says RangeError: Maximum call stack size exceeded , Firefox says InternalError: too much recursion .节点说RangeError: Maximum call stack size exceeded , Firefox 说InternalError: too much recursion

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

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