这是尾声吗? (Javascript)

Is this a tail call? (Javascript)

假设您有一个递归函数,例如:

Blah.prototype.add = function(n) {
    this.total += n;
    this.children.forEach(function(child) {
        child.add(n);
    });
};

child.add() 是尾调用吗?如果不可以这样写吗?

Are any Javascript engines tail call optimized?

JavaScript 目前不会针对

进行优化

另一种选择是蹦床 https://taylodl.wordpress.com/2013/06/07/functional-javascript-tail-call-optimization-and-trampolines/

是的,是尾调用:

function(child) {
    child.add(n);
// ^ tail
}

然而这里没有任何东西是尾递归的,因为它不是直接递归调用。

此外 this.children.forEach(…)add 方法中的尾调用。

但是,本机 forEach 方法中的回调调用可能未经过尾调用优化(除最后一个外,其他方法都不可能)。您可以通过将函数重写为

来强制执行它
Blah.prototype.add = function(n) {
    "use strict";
    this.total += n;
    let l = this.children.length;
    if (!l--)
        return;
    for (let i=0; i<l; i++)
        this.children[i].add(n);
    this.children[i].add(n); // tail-recursion
};

请注意,如果您不 return 它们的结果,这些尾调用中的 none 将被优化。