将函数引用传递给嵌套闭包

Pass a function reference to a nested closure

本文关键字:嵌套 闭包 函数 引用      更新时间:2023-09-26

在下面的代码中,我想将对驻留在父作用域上的函数的引用传递给函数"嵌套"的嵌套作用域,以便我可以从嵌套函数调用父作用域上的函数。我尝试将其作为参数传入,但它不起作用。我只是在学习/弄乱嵌套闭包,想知道是否可以做到这一点。

我希望调用nested的语法是:callme.nested()

var obj = function(val){
var access = val;
var apex = 0;
return {
    callme : (function(siblyng){
        var privatevar = 2;
        return {
            nested : function(){
                privatevar++;
                apex = privatevar;
                return access + " " + privatevar + " " + siblyng("child");
            }
        }
    })(this.sibling),
    assess : function(){
        return apex + " " + this.sibling("parent");
    },
    sibling : function(val){
        return "returned from " + val + " scope";
    }
}
}
var objref = obj(true);
console.log(objref.callme.nested());
console.log(objref.callme.nested());
console.log(objref.callme.nested());
console.log(objref.assess());
console.log(objref.sibling('global'));

如果我很了解你,你可以这样做

var obj = function(val){
var access = val;
var apex = 0;
var ret;
return (ret = {
    callme : function() {
        var privatevar = 2;
        return {
            nested : function(){
                privatevar++;
                apex = privatevar;
                return access + " " + privatevar + " " + ret.sibling("child");
            }
        };
    }(),
    assess : function(){
        return apex + " " + this.sibling("parent");
    },
    sibling : function(val){
        return "returned from " + val + " scope";
    }
  });
};
var objref = obj(true);
console.log(objref.callme.nested());
console.log(objref.callme.nested());
console.log(objref.callme.nested());
console.log(objref.assess());
console.log(objref.sibling('global'));
以下

代码中的this指向global Window对象,因此无法找到该方法。您可以在 nested 方法中直接调用 this.sibling,而无需传递它。

callme : (function(siblyng){
    var privatevar = 2;
    return {
        nested : function(){
            privatevar++;
            apex = privatevar;
            return access + " " + privatevar + " " + siblyng("child");
        }
    }
})(this.sibling),