Javascript'这'在Z组合子和其他递归函数中重写

Javascript 'this' overwriting in Z combinator and every other recursive function

本文关键字:其他 递归函数 重写 Javascript 组合      更新时间:2023-09-26

背景:

我有一个由Z-combinator实现的递归函数,如这里和这里所示,因此它没有使用arguments.callee,因为它将在即将推出的ES6中被弃用。

问题

Z-combinator和我迄今为止看到的所有递归匿名函数的主要问题是,它们将de this值更新到内部函数范围(在return子句中返回的self),因此引用顶级的this丢失了,我想通过所有内部函数来维护它。

有没有一种方法可以在不将顶级this作为额外的函数参数传递的情况下维护它,这是解决这个问题的最明显的方法,但并不像我想要的那样干净?

编辑:

现在,我通过将顶部this引用传递给Z-combinator来解决这个问题,如下所示:

Co.Utilities.Z(this.createHTMLFromLOM)(this.LOM, this);

在递归函数中,我通过像这样传递顶部的值来返回相同的函数:

function createHTMLFromLOM(callee:any, LOM_section:LOM, self:any):void {
    /* Some other code. */
    return callee(LOM_section.children[widget], self);
}

这是我的Z-combinator定义:

function Z(func:any):any {
        var f = function () {
            return func.apply(null, [f].concat([].slice.apply(arguments)));
        };
         return f;
    }

感谢

您可以执行以下操作:

var me = this;

以及将CCD_ 8作为自变量传递给Z组合器。