这是尾巴吗?(JavaScript)的

pix*_*ike 6 javascript tail-call-optimization

你有一个递归函数,如:

Blah.prototype.add = function(n) {
    this.total += n;
    this.children.forEach(function(child) {
        child.add(n);
    });
};
Run Code Online (Sandbox Code Playgroud)

child.add()尾巴吗?如果不能这样写的话呢?

Ber*_*rgi 1

是的,这是一个尾调用:

\n\n
function(child) {\n    child.add(n);\n// ^ tail\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

也是方法this.children.forEach(\xe2\x80\xa6)内的尾部调用add

\n\n

但是,本机方法中回调的调用forEach可能不是尾部调用优化的(并且除了最后一个之外的所有调用都不能优化)。您可以通过将函数重写为来强制它

\n\n
Blah.prototype.add = function(n) {\n    "use strict";\n    this.total += n;\n    let l = this.children.length;\n    if (!l--)\n        return;\n    for (let i=0; i<l; i++)\n        this.children[i].add(n);\n    this.children[i].add(n); // tail-recursion\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

请注意,如果您不了解这些尾部调用的return结果,则这些尾部调用都不会得到优化。

\n