简体   繁体   English

Z组合器和其他所有递归函数中的Javascript“ this”覆盖

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

Background: 背景:

I have a recursive function implemented by a Z-combinator as is shown here and here so it makes no use of arguments.callee since it will be deprecated in upcoming ES6 . 我有一个Z组合器实现的递归函数,如此此处所示,因此它不使用arguments.callee因为它将在即将到来的ES6中弃用。

Issue 问题

The main issue with the Z-combinator and all recursive anonymous functions I've seen so far is that they updates de this value to the inner function scope (the self-returned at the return clause), so the this that references the top level is lost, and I want to maintain it through all the inner functions. 到目前为止,我看到的Z组合器和所有递归匿名函数的主要问题是它们this值更新为内部函数作用域(在return子句中自动返回),因此this引用顶层丢失了,我想通过所有内部功能对其进行维护。

Is there a way to maintain the top level this without passing it as an additional function argument, which is the most obvious way to get rid of this issue but is not as clean as I want? 有没有保持顶层的方式this没有把它当作一个附加功能的说法,这是摆脱这一问题的最明显的方式,但不是那样干净我想要的吗?

EDIT: 编辑:

Right now I solve the issue by passing the top this reference to the Z-combinator like this: 现在,我通过将顶部解决问题this参考这样的Z-组合子

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

in the recursive function I return the same function by passing the top this value like this: 在递归函数中,我通过向顶部传递此值来返回相同的函数,如下所示:

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

This is my Z-combinator definition: 这是我的Z组合器定义:

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

Thanks 谢谢

You could do the following : 您可以执行以下操作:

var me = this;

and the pass me as an argument to the Z Combinator. 然后将me作为参数传递me Z Combinator。

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

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