Javascript 'this' overwriting in Z combina

2019-02-16 02:39发布

问题:

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.