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

六眼飞鱼酱① 提交于 2019-12-09 01:57:24

问题


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.

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.

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?

EDIT:

Right now I solve the issue by passing the top this reference to the Z-combinator like this:

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:

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

Thanks


回答1:


You could do the following :

var me = this;

and the pass me as an argument to the Z Combinator.



来源:https://stackoverflow.com/questions/18194289/javascript-this-overwriting-in-z-combinator-and-every-other-recursive-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!