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

时间:2016-04-21 16:37:42

标签: javascript closures

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

我希望调用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'));

2 个答案:

答案 0 :(得分:0)

如果我理解你,你可以这样做

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'));

答案 1 :(得分:0)

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

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